var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key2, value) => key2 in obj ? __defProp(obj, key2, {
    enumerable: true,
    configurable: true,
    writable: true,
    value
}) : obj[key2] = value;
var __publicField = (obj, key2, value) => __defNormalProp(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
var _a, _b;
import {
    a as createElementBlock,
    a8 as __vitePreload,
    a9 as useTimeoutFn,
    d as defineComponent,
    e as ref,
    o as openBlock,
    T as shallowRef,
    U as watchEffect,
    u as unref
} from "./index-Dfdf_Rjk.js";

function escapeHtml(value) {
    return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
}

let ShikiError$2 = class ShikiError extends Error {
    constructor(message) {
        super(message);
        this.name = "ShikiError";
    }
};
let ShikiError$1 = class ShikiError2 extends Error {
    constructor(message) {
        super(message);
        this.name = "ShikiError";
    }
};

function getHeapMax() {
    return 2147483648;
}

function _emscripten_get_now() {
    return typeof performance !== "undefined" ? performance.now() : Date.now();
}

const alignUp = (x, multiple) => x + (multiple - x % multiple) % multiple;

async function main(init) {
    let wasmMemory;
    let buffer;
    const binding = {};

    function updateGlobalBufferAndViews(buf) {
        buffer = buf;
        binding.HEAPU8 = new Uint8Array(buf);
        binding.HEAPU32 = new Uint32Array(buf);
    }

    function _emscripten_memcpy_big(dest, src, num) {
        binding.HEAPU8.copyWithin(dest, src, src + num);
    }

    function emscripten_realloc_buffer(size) {
        try {
            wasmMemory.grow(size - buffer.byteLength + 65535 >>> 16);
            updateGlobalBufferAndViews(wasmMemory.buffer);
            return 1;
        } catch (e) {
        }
    }

    function _emscripten_resize_heap(requestedSize) {
        const oldSize = binding.HEAPU8.length;
        requestedSize = requestedSize >>> 0;
        const maxHeapSize = getHeapMax();
        if (requestedSize > maxHeapSize)
            return false;
        for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {
            let overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
            overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
            const newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
            const replacement = emscripten_realloc_buffer(newSize);
            if (replacement)
                return true;
        }
        return false;
    }

    const UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0;

    function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead = 1024) {
        const endIdx = idx + maxBytesToRead;
        let endPtr = idx;
        while (heapOrArray[endPtr] && !(endPtr >= endIdx))
            ++endPtr;
        if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
            return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
        }
        let str = "";
        while (idx < endPtr) {
            let u0 = heapOrArray[idx++];
            if (!(u0 & 128)) {
                str += String.fromCharCode(u0);
                continue;
            }
            const u1 = heapOrArray[idx++] & 63;
            if ((u0 & 224) === 192) {
                str += String.fromCharCode((u0 & 31) << 6 | u1);
                continue;
            }
            const u2 = heapOrArray[idx++] & 63;
            if ((u0 & 240) === 224) {
                u0 = (u0 & 15) << 12 | u1 << 6 | u2;
            } else {
                u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
            }
            if (u0 < 65536) {
                str += String.fromCharCode(u0);
            } else {
                const ch = u0 - 65536;
                str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
            }
        }
        return str;
    }

    function UTF8ToString(ptr, maxBytesToRead) {
        return ptr ? UTF8ArrayToString(binding.HEAPU8, ptr, maxBytesToRead) : "";
    }

    const asmLibraryArg = {
        emscripten_get_now: _emscripten_get_now,
        emscripten_memcpy_big: _emscripten_memcpy_big,
        emscripten_resize_heap: _emscripten_resize_heap,
        fd_write: () => 0
    };

    async function createWasm() {
        const info = {
            env: asmLibraryArg,
            wasi_snapshot_preview1: asmLibraryArg
        };
        const exports = await init(info);
        wasmMemory = exports.memory;
        updateGlobalBufferAndViews(wasmMemory.buffer);
        Object.assign(binding, exports);
        binding.UTF8ToString = UTF8ToString;
    }

    await createWasm();
    return binding;
}

var __defProp2 = Object.defineProperty;
var __defNormalProp2 = (obj, key2, value) => key2 in obj ? __defProp2(obj, key2, {
    enumerable: true,
    configurable: true,
    writable: true,
    value
}) : obj[key2] = value;
var __publicField2 = (obj, key2, value) => {
    __defNormalProp2(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
    return value;
};
let onigBinding = null;

function throwLastOnigError(onigBinding2) {
    throw new ShikiError$1(onigBinding2.UTF8ToString(onigBinding2.getLastOnigError()));
}

class UtfString {
    constructor(str) {
        __publicField2(this, "utf16Length");
        __publicField2(this, "utf8Length");
        __publicField2(this, "utf16Value");
        __publicField2(this, "utf8Value");
        __publicField2(this, "utf16OffsetToUtf8");
        __publicField2(this, "utf8OffsetToUtf16");
        const utf16Length = str.length;
        const utf8Length = UtfString._utf8ByteLength(str);
        const computeIndicesMapping = utf8Length !== utf16Length;
        const utf16OffsetToUtf8 = computeIndicesMapping ? new Uint32Array(utf16Length + 1) : null;
        if (computeIndicesMapping)
            utf16OffsetToUtf8[utf16Length] = utf8Length;
        const utf8OffsetToUtf16 = computeIndicesMapping ? new Uint32Array(utf8Length + 1) : null;
        if (computeIndicesMapping)
            utf8OffsetToUtf16[utf8Length] = utf16Length;
        const utf8Value = new Uint8Array(utf8Length);
        let i8 = 0;
        for (let i16 = 0; i16 < utf16Length; i16++) {
            const charCode = str.charCodeAt(i16);
            let codePoint = charCode;
            let wasSurrogatePair = false;
            if (charCode >= 55296 && charCode <= 56319) {
                if (i16 + 1 < utf16Length) {
                    const nextCharCode = str.charCodeAt(i16 + 1);
                    if (nextCharCode >= 56320 && nextCharCode <= 57343) {
                        codePoint = (charCode - 55296 << 10) + 65536 | nextCharCode - 56320;
                        wasSurrogatePair = true;
                    }
                }
            }
            if (computeIndicesMapping) {
                utf16OffsetToUtf8[i16] = i8;
                if (wasSurrogatePair)
                    utf16OffsetToUtf8[i16 + 1] = i8;
                if (codePoint <= 127) {
                    utf8OffsetToUtf16[i8 + 0] = i16;
                } else if (codePoint <= 2047) {
                    utf8OffsetToUtf16[i8 + 0] = i16;
                    utf8OffsetToUtf16[i8 + 1] = i16;
                } else if (codePoint <= 65535) {
                    utf8OffsetToUtf16[i8 + 0] = i16;
                    utf8OffsetToUtf16[i8 + 1] = i16;
                    utf8OffsetToUtf16[i8 + 2] = i16;
                } else {
                    utf8OffsetToUtf16[i8 + 0] = i16;
                    utf8OffsetToUtf16[i8 + 1] = i16;
                    utf8OffsetToUtf16[i8 + 2] = i16;
                    utf8OffsetToUtf16[i8 + 3] = i16;
                }
            }
            if (codePoint <= 127) {
                utf8Value[i8++] = codePoint;
            } else if (codePoint <= 2047) {
                utf8Value[i8++] = 192 | (codePoint & 1984) >>> 6;
                utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
            } else if (codePoint <= 65535) {
                utf8Value[i8++] = 224 | (codePoint & 61440) >>> 12;
                utf8Value[i8++] = 128 | (codePoint & 4032) >>> 6;
                utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
            } else {
                utf8Value[i8++] = 240 | (codePoint & 1835008) >>> 18;
                utf8Value[i8++] = 128 | (codePoint & 258048) >>> 12;
                utf8Value[i8++] = 128 | (codePoint & 4032) >>> 6;
                utf8Value[i8++] = 128 | (codePoint & 63) >>> 0;
            }
            if (wasSurrogatePair)
                i16++;
        }
        this.utf16Length = utf16Length;
        this.utf8Length = utf8Length;
        this.utf16Value = str;
        this.utf8Value = utf8Value;
        this.utf16OffsetToUtf8 = utf16OffsetToUtf8;
        this.utf8OffsetToUtf16 = utf8OffsetToUtf16;
    }

    static _utf8ByteLength(str) {
        let result = 0;
        for (let i = 0, len = str.length; i < len; i++) {
            const charCode = str.charCodeAt(i);
            let codepoint = charCode;
            let wasSurrogatePair = false;
            if (charCode >= 55296 && charCode <= 56319) {
                if (i + 1 < len) {
                    const nextCharCode = str.charCodeAt(i + 1);
                    if (nextCharCode >= 56320 && nextCharCode <= 57343) {
                        codepoint = (charCode - 55296 << 10) + 65536 | nextCharCode - 56320;
                        wasSurrogatePair = true;
                    }
                }
            }
            if (codepoint <= 127)
                result += 1;
            else if (codepoint <= 2047)
                result += 2;
            else if (codepoint <= 65535)
                result += 3;
            else
                result += 4;
            if (wasSurrogatePair)
                i++;
        }
        return result;
    }

    createString(onigBinding2) {
        const result = onigBinding2.omalloc(this.utf8Length);
        onigBinding2.HEAPU8.set(this.utf8Value, result);
        return result;
    }
}

const _OnigString = class {
    constructor(str) {
        __publicField2(this, "id", ++_OnigString.LAST_ID);
        __publicField2(this, "_onigBinding");
        __publicField2(this, "content");
        __publicField2(this, "utf16Length");
        __publicField2(this, "utf8Length");
        __publicField2(this, "utf16OffsetToUtf8");
        __publicField2(this, "utf8OffsetToUtf16");
        __publicField2(this, "ptr");
        if (!onigBinding)
            throw new ShikiError$1("Must invoke loadWasm first.");
        this._onigBinding = onigBinding;
        this.content = str;
        const utfString = new UtfString(str);
        this.utf16Length = utfString.utf16Length;
        this.utf8Length = utfString.utf8Length;
        this.utf16OffsetToUtf8 = utfString.utf16OffsetToUtf8;
        this.utf8OffsetToUtf16 = utfString.utf8OffsetToUtf16;
        if (this.utf8Length < 1e4 && !_OnigString._sharedPtrInUse) {
            if (!_OnigString._sharedPtr)
                _OnigString._sharedPtr = onigBinding.omalloc(1e4);
            _OnigString._sharedPtrInUse = true;
            onigBinding.HEAPU8.set(utfString.utf8Value, _OnigString._sharedPtr);
            this.ptr = _OnigString._sharedPtr;
        } else {
            this.ptr = utfString.createString(onigBinding);
        }
    }

    convertUtf8OffsetToUtf16(utf8Offset) {
        if (this.utf8OffsetToUtf16) {
            if (utf8Offset < 0)
                return 0;
            if (utf8Offset > this.utf8Length)
                return this.utf16Length;
            return this.utf8OffsetToUtf16[utf8Offset];
        }
        return utf8Offset;
    }

    convertUtf16OffsetToUtf8(utf16Offset) {
        if (this.utf16OffsetToUtf8) {
            if (utf16Offset < 0)
                return 0;
            if (utf16Offset > this.utf16Length)
                return this.utf8Length;
            return this.utf16OffsetToUtf8[utf16Offset];
        }
        return utf16Offset;
    }

    dispose() {
        if (this.ptr === _OnigString._sharedPtr)
            _OnigString._sharedPtrInUse = false;
        else
            this._onigBinding.ofree(this.ptr);
    }
};
let OnigString = _OnigString;
__publicField2(OnigString, "LAST_ID", 0);
__publicField2(OnigString, "_sharedPtr", 0);
__publicField2(OnigString, "_sharedPtrInUse", false);

class OnigScanner {
    constructor(patterns) {
        __publicField2(this, "_onigBinding");
        __publicField2(this, "_ptr");
        if (!onigBinding)
            throw new ShikiError$1("Must invoke loadWasm first.");
        const strPtrsArr = [];
        const strLenArr = [];
        for (let i = 0, len = patterns.length; i < len; i++) {
            const utfString = new UtfString(patterns[i]);
            strPtrsArr[i] = utfString.createString(onigBinding);
            strLenArr[i] = utfString.utf8Length;
        }
        const strPtrsPtr = onigBinding.omalloc(4 * patterns.length);
        onigBinding.HEAPU32.set(strPtrsArr, strPtrsPtr / 4);
        const strLenPtr = onigBinding.omalloc(4 * patterns.length);
        onigBinding.HEAPU32.set(strLenArr, strLenPtr / 4);
        const scannerPtr = onigBinding.createOnigScanner(strPtrsPtr, strLenPtr, patterns.length);
        for (let i = 0, len = patterns.length; i < len; i++)
            onigBinding.ofree(strPtrsArr[i]);
        onigBinding.ofree(strLenPtr);
        onigBinding.ofree(strPtrsPtr);
        if (scannerPtr === 0)
            throwLastOnigError(onigBinding);
        this._onigBinding = onigBinding;
        this._ptr = scannerPtr;
    }

    dispose() {
        this._onigBinding.freeOnigScanner(this._ptr);
    }

    findNextMatchSync(string, startPosition, arg) {
        let options = 0;
        if (typeof arg === "number") {
            options = arg;
        }
        if (typeof string === "string") {
            string = new OnigString(string);
            const result = this._findNextMatchSync(string, startPosition, false, options);
            string.dispose();
            return result;
        }
        return this._findNextMatchSync(string, startPosition, false, options);
    }

    _findNextMatchSync(string, startPosition, debugCall, options) {
        const onigBinding2 = this._onigBinding;
        const resultPtr = onigBinding2.findNextOnigScannerMatch(this._ptr, string.id, string.ptr, string.utf8Length, string.convertUtf16OffsetToUtf8(startPosition), options);
        if (resultPtr === 0) {
            return null;
        }
        const HEAPU32 = onigBinding2.HEAPU32;
        let offset = resultPtr / 4;
        const index = HEAPU32[offset++];
        const count = HEAPU32[offset++];
        const captureIndices = [];
        for (let i = 0; i < count; i++) {
            const beg = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);
            const end = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);
            captureIndices[i] = {
                start: beg,
                end,
                length: end - beg
            };
        }
        return {
            index,
            captureIndices
        };
    }
}

function isInstantiatorOptionsObject(dataOrOptions) {
    return typeof dataOrOptions.instantiator === "function";
}

function isInstantiatorModule(dataOrOptions) {
    return typeof dataOrOptions.default === "function";
}

function isDataOptionsObject(dataOrOptions) {
    return typeof dataOrOptions.data !== "undefined";
}

function isResponse(dataOrOptions) {
    return typeof Response !== "undefined" && dataOrOptions instanceof Response;
}

function isArrayBuffer(data) {
    var _a2;
    return typeof ArrayBuffer !== "undefined" && (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) || typeof Buffer !== "undefined" && ((_a2 = Buffer.isBuffer) == null ? void 0 : _a2.call(Buffer, data)) || typeof SharedArrayBuffer !== "undefined" && data instanceof SharedArrayBuffer || typeof Uint32Array !== "undefined" && data instanceof Uint32Array;
}

let initPromise;

function loadWasm(options) {
    if (initPromise)
        return initPromise;

    async function _load() {
        onigBinding = await main(async (info) => {
            let instance = options;
            instance = await instance;
            if (typeof instance === "function")
                instance = await instance(info);
            if (typeof instance === "function")
                instance = await instance(info);
            if (isInstantiatorOptionsObject(instance)) {
                instance = await instance.instantiator(info);
            } else if (isInstantiatorModule(instance)) {
                instance = await instance.default(info);
            } else {
                if (isDataOptionsObject(instance))
                    instance = instance.data;
                if (isResponse(instance)) {
                    if (typeof WebAssembly.instantiateStreaming === "function")
                        instance = await _makeResponseStreamingLoader(instance)(info);
                    else
                        instance = await _makeResponseNonStreamingLoader(instance)(info);
                } else if (isArrayBuffer(instance)) {
                    instance = await _makeArrayBufferLoader(instance)(info);
                } else if (instance instanceof WebAssembly.Module) {
                    instance = await _makeArrayBufferLoader(instance)(info);
                } else if ("default" in instance && instance.default instanceof WebAssembly.Module) {
                    instance = await _makeArrayBufferLoader(instance.default)(info);
                }
            }
            if ("instance" in instance)
                instance = instance.instance;
            if ("exports" in instance)
                instance = instance.exports;
            return instance;
        });
    }

    initPromise = _load();
    return initPromise;
}

function _makeArrayBufferLoader(data) {
    return (importObject) => WebAssembly.instantiate(data, importObject);
}

function _makeResponseStreamingLoader(data) {
    return (importObject) => WebAssembly.instantiateStreaming(data, importObject);
}

function _makeResponseNonStreamingLoader(data) {
    return async (importObject) => {
        const arrayBuffer = await data.arrayBuffer();
        return WebAssembly.instantiate(arrayBuffer, importObject);
    };
}

let _defaultWasmLoader;

function getDefaultWasmLoader() {
    return _defaultWasmLoader;
}

async function createOnigurumaEngine(options) {
    if (options)
        await loadWasm(options);
    return {
        createScanner(patterns) {
            return new OnigScanner(patterns.map((p2) => typeof p2 === "string" ? p2 : p2.source));
        },
        createString(s) {
            return new OnigString(s);
        }
    };
}

let _emitDeprecation = 3;

function warnDeprecated(message, version = 3) {
    if (version > _emitDeprecation)
        return;
    {
        console.trace("[SHIKI DEPRECATE]: ".concat(message));
    }
}

function clone(something) {
    return doClone(something);
}

function doClone(something) {
    if (Array.isArray(something)) {
        return cloneArray(something);
    }
    if (something instanceof RegExp) {
        return something;
    }
    if (typeof something === "object") {
        return cloneObj(something);
    }
    return something;
}

function cloneArray(arr) {
    let r = [];
    for (let i = 0, len = arr.length; i < len; i++) {
        r[i] = doClone(arr[i]);
    }
    return r;
}

function cloneObj(obj) {
    let r = {};
    for (let key2 in obj) {
        r[key2] = doClone(obj[key2]);
    }
    return r;
}

function mergeObjects(target, ...sources) {
    sources.forEach((source) => {
        for (let key2 in source) {
            target[key2] = source[key2];
        }
    });
    return target;
}

function basename(path) {
    const idx = ~path.lastIndexOf("/") || ~path.lastIndexOf("\\");
    if (idx === 0) {
        return path;
    } else if (~idx === path.length - 1) {
        return basename(path.substring(0, path.length - 1));
    } else {
        return path.substr(~idx + 1);
    }
}

var CAPTURING_REGEX_SOURCE = /\$(\d+)|\${(\d+):\/(downcase|upcase)}/g;
var RegexSource = class {
    static hasCaptures(regexSource) {
        if (regexSource === null) {
            return false;
        }
        CAPTURING_REGEX_SOURCE.lastIndex = 0;
        return CAPTURING_REGEX_SOURCE.test(regexSource);
    }

    static replaceCaptures(regexSource, captureSource, captureIndices) {
        return regexSource.replace(CAPTURING_REGEX_SOURCE, (match, index, commandIndex, command) => {
            let capture = captureIndices[parseInt(index || commandIndex, 10)];
            if (capture) {
                let result = captureSource.substring(capture.start, capture.end);
                while (result[0] === ".") {
                    result = result.substring(1);
                }
                switch (command) {
                    case "downcase":
                        return result.toLowerCase();
                    case "upcase":
                        return result.toUpperCase();
                    default:
                        return result;
                }
            } else {
                return match;
            }
        });
    }
};

function strcmp(a, b) {
    if (a < b) {
        return -1;
    }
    if (a > b) {
        return 1;
    }
    return 0;
}

function strArrCmp(a, b) {
    if (a === null && b === null) {
        return 0;
    }
    if (!a) {
        return -1;
    }
    if (!b) {
        return 1;
    }
    let len1 = a.length;
    let len2 = b.length;
    if (len1 === len2) {
        for (let i = 0; i < len1; i++) {
            let res = strcmp(a[i], b[i]);
            if (res !== 0) {
                return res;
            }
        }
        return 0;
    }
    return len1 - len2;
}

function isValidHexColor(hex) {
    if (/^#[0-9a-f]{6}$/i.test(hex)) {
        return true;
    }
    if (/^#[0-9a-f]{8}$/i.test(hex)) {
        return true;
    }
    if (/^#[0-9a-f]{3}$/i.test(hex)) {
        return true;
    }
    if (/^#[0-9a-f]{4}$/i.test(hex)) {
        return true;
    }
    return false;
}

function escapeRegExpCharacters(value) {
    return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&");
}

var CachedFn = class {
    constructor(fn) {
        __publicField(this, "cache", /* @__PURE__ */ new Map());
        this.fn = fn;
    }

    get(key2) {
        if (this.cache.has(key2)) {
            return this.cache.get(key2);
        }
        const value = this.fn(key2);
        this.cache.set(key2, value);
        return value;
    }
};
var Theme = class {
    constructor(_colorMap, _defaults, _root) {
        __publicField(this, "_cachedMatchRoot", new CachedFn(
            (scopeName) => this._root.match(scopeName)
        ));
        this._colorMap = _colorMap;
        this._defaults = _defaults;
        this._root = _root;
    }

    static createFromRawTheme(source, colorMap) {
        return this.createFromParsedTheme(parseTheme(source), colorMap);
    }

    static createFromParsedTheme(source, colorMap) {
        return resolveParsedThemeRules(source, colorMap);
    }

    getColorMap() {
        return this._colorMap.getColorMap();
    }

    getDefaults() {
        return this._defaults;
    }

    match(scopePath) {
        if (scopePath === null) {
            return this._defaults;
        }
        const scopeName = scopePath.scopeName;
        const matchingTrieElements = this._cachedMatchRoot.get(scopeName);
        const effectiveRule = matchingTrieElements.find(
            (v) => _scopePathMatchesParentScopes(scopePath.parent, v.parentScopes)
        );
        if (!effectiveRule) {
            return null;
        }
        return new StyleAttributes(
            effectiveRule.fontStyle,
            effectiveRule.foreground,
            effectiveRule.background
        );
    }
};
var ScopeStack = class _ScopeStack {
    constructor(parent, scopeName) {
        this.parent = parent;
        this.scopeName = scopeName;
    }

    static push(path, scopeNames) {
        for (const name of scopeNames) {
            path = new _ScopeStack(path, name);
        }
        return path;
    }

    static from(...segments) {
        let result = null;
        for (let i = 0; i < segments.length; i++) {
            result = new _ScopeStack(result, segments[i]);
        }
        return result;
    }

    push(scopeName) {
        return new _ScopeStack(this, scopeName);
    }

    getSegments() {
        let item = this;
        const result = [];
        while (item) {
            result.push(item.scopeName);
            item = item.parent;
        }
        result.reverse();
        return result;
    }

    toString() {
        return this.getSegments().join(" ");
    }

    extends(other) {
        if (this === other) {
            return true;
        }
        if (this.parent === null) {
            return false;
        }
        return this.parent.extends(other);
    }

    getExtensionIfDefined(base) {
        const result = [];
        let item = this;
        while (item && item !== base) {
            result.push(item.scopeName);
            item = item.parent;
        }
        return item === base ? result.reverse() : void 0;
    }
};

function _scopePathMatchesParentScopes(scopePath, parentScopes) {
    if (parentScopes.length === 0) {
        return true;
    }
    for (let index = 0; index < parentScopes.length; index++) {
        let scopePattern = parentScopes[index];
        let scopeMustMatch = false;
        if (scopePattern === ">") {
            if (index === parentScopes.length - 1) {
                return false;
            }
            scopePattern = parentScopes[++index];
            scopeMustMatch = true;
        }
        while (scopePath) {
            if (_matchesScope(scopePath.scopeName, scopePattern)) {
                break;
            }
            if (scopeMustMatch) {
                return false;
            }
            scopePath = scopePath.parent;
        }
        if (!scopePath) {
            return false;
        }
        scopePath = scopePath.parent;
    }
    return true;
}

function _matchesScope(scopeName, scopePattern) {
    return scopePattern === scopeName || scopeName.startsWith(scopePattern) && scopeName[scopePattern.length] === ".";
}

var StyleAttributes = class {
    constructor(fontStyle, foregroundId, backgroundId) {
        this.fontStyle = fontStyle;
        this.foregroundId = foregroundId;
        this.backgroundId = backgroundId;
    }
};

function parseTheme(source) {
    if (!source) {
        return [];
    }
    if (!source.settings || !Array.isArray(source.settings)) {
        return [];
    }
    let settings = source.settings;
    let result = [], resultLen = 0;
    for (let i = 0, len = settings.length; i < len; i++) {
        let entry = settings[i];
        if (!entry.settings) {
            continue;
        }
        let scopes;
        if (typeof entry.scope === "string") {
            let _scope = entry.scope;
            _scope = _scope.replace(/^[,]+/, "");
            _scope = _scope.replace(/[,]+$/, "");
            scopes = _scope.split(",");
        } else if (Array.isArray(entry.scope)) {
            scopes = entry.scope;
        } else {
            scopes = [""];
        }
        let fontStyle = -1;
        if (typeof entry.settings.fontStyle === "string") {
            fontStyle = 0;
            let segments = entry.settings.fontStyle.split(" ");
            for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
                let segment = segments[j];
                switch (segment) {
                    case "italic":
                        fontStyle = fontStyle | 1;
                        break;
                    case "bold":
                        fontStyle = fontStyle | 2;
                        break;
                    case "underline":
                        fontStyle = fontStyle | 4;
                        break;
                    case "strikethrough":
                        fontStyle = fontStyle | 8;
                        break;
                }
            }
        }
        let foreground = null;
        if (typeof entry.settings.foreground === "string" && isValidHexColor(entry.settings.foreground)) {
            foreground = entry.settings.foreground;
        }
        let background = null;
        if (typeof entry.settings.background === "string" && isValidHexColor(entry.settings.background)) {
            background = entry.settings.background;
        }
        for (let j = 0, lenJ = scopes.length; j < lenJ; j++) {
            let _scope = scopes[j].trim();
            let segments = _scope.split(" ");
            let scope = segments[segments.length - 1];
            let parentScopes = null;
            if (segments.length > 1) {
                parentScopes = segments.slice(0, segments.length - 1);
                parentScopes.reverse();
            }
            result[resultLen++] = new ParsedThemeRule(
                scope,
                parentScopes,
                i,
                fontStyle,
                foreground,
                background
            );
        }
    }
    return result;
}

var ParsedThemeRule = class {
    constructor(scope, parentScopes, index, fontStyle, foreground, background) {
        this.scope = scope;
        this.parentScopes = parentScopes;
        this.index = index;
        this.fontStyle = fontStyle;
        this.foreground = foreground;
        this.background = background;
    }
};
var FontStyle = /* @__PURE__ */ ((FontStyle2) => {
    FontStyle2[FontStyle2["NotSet"] = -1] = "NotSet";
    FontStyle2[FontStyle2["None"] = 0] = "None";
    FontStyle2[FontStyle2["Italic"] = 1] = "Italic";
    FontStyle2[FontStyle2["Bold"] = 2] = "Bold";
    FontStyle2[FontStyle2["Underline"] = 4] = "Underline";
    FontStyle2[FontStyle2["Strikethrough"] = 8] = "Strikethrough";
    return FontStyle2;
})(FontStyle || {});

function resolveParsedThemeRules(parsedThemeRules, _colorMap) {
    parsedThemeRules.sort((a, b) => {
        let r = strcmp(a.scope, b.scope);
        if (r !== 0) {
            return r;
        }
        r = strArrCmp(a.parentScopes, b.parentScopes);
        if (r !== 0) {
            return r;
        }
        return a.index - b.index;
    });
    let defaultFontStyle = 0;
    let defaultForeground = "#000000";
    let defaultBackground = "#ffffff";
    while (parsedThemeRules.length >= 1 && parsedThemeRules[0].scope === "") {
        let incomingDefaults = parsedThemeRules.shift();
        if (incomingDefaults.fontStyle !== -1) {
            defaultFontStyle = incomingDefaults.fontStyle;
        }
        if (incomingDefaults.foreground !== null) {
            defaultForeground = incomingDefaults.foreground;
        }
        if (incomingDefaults.background !== null) {
            defaultBackground = incomingDefaults.background;
        }
    }
    let colorMap = new ColorMap(_colorMap);
    let defaults = new StyleAttributes(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));
    let root2 = new ThemeTrieElement(new ThemeTrieElementRule(0, null, -1, 0, 0), []);
    for (let i = 0, len = parsedThemeRules.length; i < len; i++) {
        let rule = parsedThemeRules[i];
        root2.insert(0, rule.scope, rule.parentScopes, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));
    }
    return new Theme(colorMap, defaults, root2);
}

var ColorMap = class {
    constructor(_colorMap) {
        __publicField(this, "_isFrozen");
        __publicField(this, "_lastColorId");
        __publicField(this, "_id2color");
        __publicField(this, "_color2id");
        this._lastColorId = 0;
        this._id2color = [];
        this._color2id = /* @__PURE__ */ Object.create(null);
        if (Array.isArray(_colorMap)) {
            this._isFrozen = true;
            for (let i = 0, len = _colorMap.length; i < len; i++) {
                this._color2id[_colorMap[i]] = i;
                this._id2color[i] = _colorMap[i];
            }
        } else {
            this._isFrozen = false;
        }
    }

    getId(color) {
        if (color === null) {
            return 0;
        }
        color = color.toUpperCase();
        let value = this._color2id[color];
        if (value) {
            return value;
        }
        if (this._isFrozen) {
            throw new Error("Missing color in color map - ".concat(color));
        }
        value = ++this._lastColorId;
        this._color2id[color] = value;
        this._id2color[value] = color;
        return value;
    }

    getColorMap() {
        return this._id2color.slice(0);
    }
};
var emptyParentScopes = Object.freeze([]);
var ThemeTrieElementRule = class _ThemeTrieElementRule {
    constructor(scopeDepth, parentScopes, fontStyle, foreground, background) {
        __publicField(this, "scopeDepth");
        __publicField(this, "parentScopes");
        __publicField(this, "fontStyle");
        __publicField(this, "foreground");
        __publicField(this, "background");
        this.scopeDepth = scopeDepth;
        this.parentScopes = parentScopes || emptyParentScopes;
        this.fontStyle = fontStyle;
        this.foreground = foreground;
        this.background = background;
    }

    static cloneArr(arr) {
        let r = [];
        for (let i = 0, len = arr.length; i < len; i++) {
            r[i] = arr[i].clone();
        }
        return r;
    }

    clone() {
        return new _ThemeTrieElementRule(this.scopeDepth, this.parentScopes, this.fontStyle, this.foreground, this.background);
    }

    acceptOverwrite(scopeDepth, fontStyle, foreground, background) {
        if (this.scopeDepth > scopeDepth) {
            console.log("how did this happen?");
        } else {
            this.scopeDepth = scopeDepth;
        }
        if (fontStyle !== -1) {
            this.fontStyle = fontStyle;
        }
        if (foreground !== 0) {
            this.foreground = foreground;
        }
        if (background !== 0) {
            this.background = background;
        }
    }
};
var ThemeTrieElement = class _ThemeTrieElement {
    constructor(_mainRule, rulesWithParentScopes = [], _children = {}) {
        __publicField(this, "_rulesWithParentScopes");
        this._mainRule = _mainRule;
        this._children = _children;
        this._rulesWithParentScopes = rulesWithParentScopes;
    }

    static _cmpBySpecificity(a, b) {
        if (a.scopeDepth !== b.scopeDepth) {
            return b.scopeDepth - a.scopeDepth;
        }
        let aParentIndex = 0;
        let bParentIndex = 0;
        while (true) {
            if (a.parentScopes[aParentIndex] === ">") {
                aParentIndex++;
            }
            if (b.parentScopes[bParentIndex] === ">") {
                bParentIndex++;
            }
            if (aParentIndex >= a.parentScopes.length || bParentIndex >= b.parentScopes.length) {
                break;
            }
            const parentScopeLengthDiff = b.parentScopes[bParentIndex].length - a.parentScopes[aParentIndex].length;
            if (parentScopeLengthDiff !== 0) {
                return parentScopeLengthDiff;
            }
            aParentIndex++;
            bParentIndex++;
        }
        return b.parentScopes.length - a.parentScopes.length;
    }

    match(scope) {
        if (scope !== "") {
            let dotIndex = scope.indexOf(".");
            let head2;
            let tail;
            if (dotIndex === -1) {
                head2 = scope;
                tail = "";
            } else {
                head2 = scope.substring(0, dotIndex);
                tail = scope.substring(dotIndex + 1);
            }
            if (this._children.hasOwnProperty(head2)) {
                return this._children[head2].match(tail);
            }
        }
        const rules = this._rulesWithParentScopes.concat(this._mainRule);
        rules.sort(_ThemeTrieElement._cmpBySpecificity);
        return rules;
    }

    insert(scopeDepth, scope, parentScopes, fontStyle, foreground, background) {
        if (scope === "") {
            this._doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background);
            return;
        }
        let dotIndex = scope.indexOf(".");
        let head2;
        let tail;
        if (dotIndex === -1) {
            head2 = scope;
            tail = "";
        } else {
            head2 = scope.substring(0, dotIndex);
            tail = scope.substring(dotIndex + 1);
        }
        let child;
        if (this._children.hasOwnProperty(head2)) {
            child = this._children[head2];
        } else {
            child = new _ThemeTrieElement(this._mainRule.clone(), ThemeTrieElementRule.cloneArr(this._rulesWithParentScopes));
            this._children[head2] = child;
        }
        child.insert(scopeDepth + 1, tail, parentScopes, fontStyle, foreground, background);
    }

    _doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background) {
        if (parentScopes === null) {
            this._mainRule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);
            return;
        }
        for (let i = 0, len = this._rulesWithParentScopes.length; i < len; i++) {
            let rule = this._rulesWithParentScopes[i];
            if (strArrCmp(rule.parentScopes, parentScopes) === 0) {
                rule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);
                return;
            }
        }
        if (fontStyle === -1) {
            fontStyle = this._mainRule.fontStyle;
        }
        if (foreground === 0) {
            foreground = this._mainRule.foreground;
        }
        if (background === 0) {
            background = this._mainRule.background;
        }
        this._rulesWithParentScopes.push(new ThemeTrieElementRule(scopeDepth, parentScopes, fontStyle, foreground, background));
    }
};
var EncodedTokenMetadata = class _EncodedTokenMetadata {
    static toBinaryStr(encodedTokenAttributes) {
        return encodedTokenAttributes.toString(2).padStart(32, "0");
    }

    static print(encodedTokenAttributes) {
        const languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);
        const tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);
        const fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);
        const foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);
        const background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);
        console.log({
            languageId,
            tokenType,
            fontStyle,
            foreground,
            background
        });
    }

    static getLanguageId(encodedTokenAttributes) {
        return (encodedTokenAttributes & 255) >>> 0;
    }

    static getTokenType(encodedTokenAttributes) {
        return (encodedTokenAttributes & 768) >>> 8;
    }

    static containsBalancedBrackets(encodedTokenAttributes) {
        return (encodedTokenAttributes & 1024) !== 0;
    }

    static getFontStyle(encodedTokenAttributes) {
        return (encodedTokenAttributes & 30720) >>> 11;
    }

    static getForeground(encodedTokenAttributes) {
        return (encodedTokenAttributes & 16744448) >>> 15;
    }

    static getBackground(encodedTokenAttributes) {
        return (encodedTokenAttributes & 4278190080) >>> 24;
    }

    /**
     * Updates the fields in `metadata`.
     * A value of `0`, `NotSet` or `null` indicates that the corresponding field should be left as is.
     */
    static set(encodedTokenAttributes, languageId, tokenType, containsBalancedBrackets, fontStyle, foreground, background) {
        let _languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);
        let _tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);
        let _containsBalancedBracketsBit = _EncodedTokenMetadata.containsBalancedBrackets(encodedTokenAttributes) ? 1 : 0;
        let _fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);
        let _foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);
        let _background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);
        if (languageId !== 0) {
            _languageId = languageId;
        }
        if (tokenType !== 8) {
            _tokenType = fromOptionalTokenType(tokenType);
        }
        if (containsBalancedBrackets !== null) {
            _containsBalancedBracketsBit = containsBalancedBrackets ? 1 : 0;
        }
        if (fontStyle !== -1) {
            _fontStyle = fontStyle;
        }
        if (foreground !== 0) {
            _foreground = foreground;
        }
        if (background !== 0) {
            _background = background;
        }
        return (_languageId << 0 | _tokenType << 8 | _containsBalancedBracketsBit << 10 | _fontStyle << 11 | _foreground << 15 | _background << 24) >>> 0;
    }
};

function toOptionalTokenType(standardType) {
    return standardType;
}

function fromOptionalTokenType(standardType) {
    return standardType;
}

function createMatchers(selector, matchesName) {
    const results = [];
    const tokenizer = newTokenizer(selector);
    let token = tokenizer.next();
    while (token !== null) {
        let priority = 0;
        if (token.length === 2 && token.charAt(1) === ":") {
            switch (token.charAt(0)) {
                case "R":
                    priority = 1;
                    break;
                case "L":
                    priority = -1;
                    break;
                default:
                    console.log("Unknown priority ".concat(token, " in scope selector"));
            }
            token = tokenizer.next();
        }
        let matcher = parseConjunction();
        results.push({matcher, priority});
        if (token !== ",") {
            break;
        }
        token = tokenizer.next();
    }
    return results;

    function parseOperand() {
        if (token === "-") {
            token = tokenizer.next();
            const expressionToNegate = parseOperand();
            return (matcherInput) => !!expressionToNegate && !expressionToNegate(matcherInput);
        }
        if (token === "(") {
            token = tokenizer.next();
            const expressionInParents = parseInnerExpression();
            if (token === ")") {
                token = tokenizer.next();
            }
            return expressionInParents;
        }
        if (isIdentifier(token)) {
            const identifiers = [];
            do {
                identifiers.push(token);
                token = tokenizer.next();
            } while (isIdentifier(token));
            return (matcherInput) => matchesName(identifiers, matcherInput);
        }
        return null;
    }

    function parseConjunction() {
        const matchers = [];
        let matcher = parseOperand();
        while (matcher) {
            matchers.push(matcher);
            matcher = parseOperand();
        }
        return (matcherInput) => matchers.every((matcher2) => matcher2(matcherInput));
    }

    function parseInnerExpression() {
        const matchers = [];
        let matcher = parseConjunction();
        while (matcher) {
            matchers.push(matcher);
            if (token === "|" || token === ",") {
                do {
                    token = tokenizer.next();
                } while (token === "|" || token === ",");
            } else {
                break;
            }
            matcher = parseConjunction();
        }
        return (matcherInput) => matchers.some((matcher2) => matcher2(matcherInput));
    }
}

function isIdentifier(token) {
    return !!token && !!token.match(/[\w\.:]+/);
}

function newTokenizer(input) {
    let regex = /([LR]:|[\w\.:][\w\.:\-]*|[\,\|\-\(\)])/g;
    let match = regex.exec(input);
    return {
        next: () => {
            if (!match) {
                return null;
            }
            const res = match[0];
            match = regex.exec(input);
            return res;
        }
    };
}

function disposeOnigString(str) {
    if (typeof str.dispose === "function") {
        str.dispose();
    }
}

var TopLevelRuleReference = class {
    constructor(scopeName) {
        this.scopeName = scopeName;
    }

    toKey() {
        return this.scopeName;
    }
};
var TopLevelRepositoryRuleReference = class {
    constructor(scopeName, ruleName) {
        this.scopeName = scopeName;
        this.ruleName = ruleName;
    }

    toKey() {
        return "".concat(this.scopeName, "#").concat(this.ruleName);
    }
};
var ExternalReferenceCollector = class {
    constructor() {
        __publicField(this, "_references", []);
        __publicField(this, "_seenReferenceKeys", /* @__PURE__ */ new Set());
        __publicField(this, "visitedRule", /* @__PURE__ */ new Set());
    }

    get references() {
        return this._references;
    }

    add(reference) {
        const key2 = reference.toKey();
        if (this._seenReferenceKeys.has(key2)) {
            return;
        }
        this._seenReferenceKeys.add(key2);
        this._references.push(reference);
    }
};
var ScopeDependencyProcessor = class {
    constructor(repo, initialScopeName) {
        __publicField(this, "seenFullScopeRequests", /* @__PURE__ */ new Set());
        __publicField(this, "seenPartialScopeRequests", /* @__PURE__ */ new Set());
        __publicField(this, "Q");
        this.repo = repo;
        this.initialScopeName = initialScopeName;
        this.seenFullScopeRequests.add(this.initialScopeName);
        this.Q = [new TopLevelRuleReference(this.initialScopeName)];
    }

    processQueue() {
        const q = this.Q;
        this.Q = [];
        const deps = new ExternalReferenceCollector();
        for (const dep of q) {
            collectReferencesOfReference(dep, this.initialScopeName, this.repo, deps);
        }
        for (const dep of deps.references) {
            if (dep instanceof TopLevelRuleReference) {
                if (this.seenFullScopeRequests.has(dep.scopeName)) {
                    continue;
                }
                this.seenFullScopeRequests.add(dep.scopeName);
                this.Q.push(dep);
            } else {
                if (this.seenFullScopeRequests.has(dep.scopeName)) {
                    continue;
                }
                if (this.seenPartialScopeRequests.has(dep.toKey())) {
                    continue;
                }
                this.seenPartialScopeRequests.add(dep.toKey());
                this.Q.push(dep);
            }
        }
    }
};

function collectReferencesOfReference(reference, baseGrammarScopeName, repo, result) {
    const selfGrammar = repo.lookup(reference.scopeName);
    if (!selfGrammar) {
        if (reference.scopeName === baseGrammarScopeName) {
            throw new Error("No grammar provided for <".concat(baseGrammarScopeName, ">"));
        }
        return;
    }
    const baseGrammar = repo.lookup(baseGrammarScopeName);
    if (reference instanceof TopLevelRuleReference) {
        collectExternalReferencesInTopLevelRule({baseGrammar, selfGrammar}, result);
    } else {
        collectExternalReferencesInTopLevelRepositoryRule(
            reference.ruleName,
            {baseGrammar, selfGrammar, repository: selfGrammar.repository},
            result
        );
    }
    const injections = repo.injections(reference.scopeName);
    if (injections) {
        for (const injection of injections) {
            result.add(new TopLevelRuleReference(injection));
        }
    }
}

function collectExternalReferencesInTopLevelRepositoryRule(ruleName, context, result) {
    if (context.repository && context.repository[ruleName]) {
        const rule = context.repository[ruleName];
        collectExternalReferencesInRules([rule], context, result);
    }
}

function collectExternalReferencesInTopLevelRule(context, result) {
    if (context.selfGrammar.patterns && Array.isArray(context.selfGrammar.patterns)) {
        collectExternalReferencesInRules(
            context.selfGrammar.patterns,
            {...context, repository: context.selfGrammar.repository},
            result
        );
    }
    if (context.selfGrammar.injections) {
        collectExternalReferencesInRules(
            Object.values(context.selfGrammar.injections),
            {...context, repository: context.selfGrammar.repository},
            result
        );
    }
}

function collectExternalReferencesInRules(rules, context, result) {
    for (const rule of rules) {
        if (result.visitedRule.has(rule)) {
            continue;
        }
        result.visitedRule.add(rule);
        const patternRepository = rule.repository ? mergeObjects({}, context.repository, rule.repository) : context.repository;
        if (Array.isArray(rule.patterns)) {
            collectExternalReferencesInRules(rule.patterns, {...context, repository: patternRepository}, result);
        }
        const include = rule.include;
        if (!include) {
            continue;
        }
        const reference = parseInclude(include);
        switch (reference.kind) {
            case 0:
                collectExternalReferencesInTopLevelRule({...context, selfGrammar: context.baseGrammar}, result);
                break;
            case 1:
                collectExternalReferencesInTopLevelRule(context, result);
                break;
            case 2:
                collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, {
                    ...context,
                    repository: patternRepository
                }, result);
                break;
            case 3:
            case 4:
                const selfGrammar = reference.scopeName === context.selfGrammar.scopeName ? context.selfGrammar : reference.scopeName === context.baseGrammar.scopeName ? context.baseGrammar : void 0;
                if (selfGrammar) {
                    const newContext = {baseGrammar: context.baseGrammar, selfGrammar, repository: patternRepository};
                    if (reference.kind === 4) {
                        collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, newContext, result);
                    } else {
                        collectExternalReferencesInTopLevelRule(newContext, result);
                    }
                } else {
                    if (reference.kind === 4) {
                        result.add(new TopLevelRepositoryRuleReference(reference.scopeName, reference.ruleName));
                    } else {
                        result.add(new TopLevelRuleReference(reference.scopeName));
                    }
                }
                break;
        }
    }
}

var BaseReference = class {
    constructor() {
        __publicField(this, "kind", 0);
    }
};
var SelfReference = class {
    constructor() {
        __publicField(this, "kind", 1);
    }
};
var RelativeReference = class {
    constructor(ruleName) {
        __publicField(this, "kind", 2);
        this.ruleName = ruleName;
    }
};
var TopLevelReference = class {
    constructor(scopeName) {
        __publicField(this, "kind", 3);
        this.scopeName = scopeName;
    }
};
var TopLevelRepositoryReference = class {
    constructor(scopeName, ruleName) {
        __publicField(this, "kind", 4);
        this.scopeName = scopeName;
        this.ruleName = ruleName;
    }
};

function parseInclude(include) {
    if (include === "$base") {
        return new BaseReference();
    } else if (include === "$self") {
        return new SelfReference();
    }
    const indexOfSharp = include.indexOf("#");
    if (indexOfSharp === -1) {
        return new TopLevelReference(include);
    } else if (indexOfSharp === 0) {
        return new RelativeReference(include.substring(1));
    } else {
        const scopeName = include.substring(0, indexOfSharp);
        const ruleName = include.substring(indexOfSharp + 1);
        return new TopLevelRepositoryReference(scopeName, ruleName);
    }
}

var HAS_BACK_REFERENCES = /\\(\d+)/;
var BACK_REFERENCING_END = /\\(\d+)/g;
var endRuleId = -1;
var whileRuleId = -2;

function ruleIdFromNumber(id) {
    return id;
}

function ruleIdToNumber(id) {
    return id;
}

var Rule = class {
    constructor($location, id, name, contentName) {
        __publicField(this, "$location");
        __publicField(this, "id");
        __publicField(this, "_nameIsCapturing");
        __publicField(this, "_name");
        __publicField(this, "_contentNameIsCapturing");
        __publicField(this, "_contentName");
        this.$location = $location;
        this.id = id;
        this._name = name || null;
        this._nameIsCapturing = RegexSource.hasCaptures(this._name);
        this._contentName = contentName || null;
        this._contentNameIsCapturing = RegexSource.hasCaptures(this._contentName);
    }

    get debugName() {
        const location = this.$location ? "".concat(basename(this.$location.filename), ":").concat(this.$location.line) : "unknown";
        return "".concat(this.constructor.name, "#").concat(this.id, " @ ").concat(location);
    }

    getName(lineText, captureIndices) {
        if (!this._nameIsCapturing || this._name === null || lineText === null || captureIndices === null) {
            return this._name;
        }
        return RegexSource.replaceCaptures(this._name, lineText, captureIndices);
    }

    getContentName(lineText, captureIndices) {
        if (!this._contentNameIsCapturing || this._contentName === null) {
            return this._contentName;
        }
        return RegexSource.replaceCaptures(this._contentName, lineText, captureIndices);
    }
};
var CaptureRule = class extends Rule {
    constructor($location, id, name, contentName, retokenizeCapturedWithRuleId) {
        super($location, id, name, contentName);
        __publicField(this, "retokenizeCapturedWithRuleId");
        this.retokenizeCapturedWithRuleId = retokenizeCapturedWithRuleId;
    }

    dispose() {
    }

    collectPatterns(grammar, out) {
        throw new Error("Not supported!");
    }

    compile(grammar, endRegexSource) {
        throw new Error("Not supported!");
    }

    compileAG(grammar, endRegexSource, allowA, allowG) {
        throw new Error("Not supported!");
    }
};
var MatchRule = class extends Rule {
    constructor($location, id, name, match, captures) {
        super($location, id, name, null);
        __publicField(this, "_match");
        __publicField(this, "captures");
        __publicField(this, "_cachedCompiledPatterns");
        this._match = new RegExpSource(match, this.id);
        this.captures = captures;
        this._cachedCompiledPatterns = null;
    }

    get debugMatchRegExp() {
        return "".concat(this._match.source);
    }

    dispose() {
        if (this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns.dispose();
            this._cachedCompiledPatterns = null;
        }
    }

    collectPatterns(grammar, out) {
        out.push(this._match);
    }

    compile(grammar, endRegexSource) {
        return this._getCachedCompiledPatterns(grammar).compile(grammar);
    }

    compileAG(grammar, endRegexSource, allowA, allowG) {
        return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
    }

    _getCachedCompiledPatterns(grammar) {
        if (!this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns = new RegExpSourceList();
            this.collectPatterns(grammar, this._cachedCompiledPatterns);
        }
        return this._cachedCompiledPatterns;
    }
};
var IncludeOnlyRule = class extends Rule {
    constructor($location, id, name, contentName, patterns) {
        super($location, id, name, contentName);
        __publicField(this, "hasMissingPatterns");
        __publicField(this, "patterns");
        __publicField(this, "_cachedCompiledPatterns");
        this.patterns = patterns.patterns;
        this.hasMissingPatterns = patterns.hasMissingPatterns;
        this._cachedCompiledPatterns = null;
    }

    dispose() {
        if (this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns.dispose();
            this._cachedCompiledPatterns = null;
        }
    }

    collectPatterns(grammar, out) {
        for (const pattern of this.patterns) {
            const rule = grammar.getRule(pattern);
            rule.collectPatterns(grammar, out);
        }
    }

    compile(grammar, endRegexSource) {
        return this._getCachedCompiledPatterns(grammar).compile(grammar);
    }

    compileAG(grammar, endRegexSource, allowA, allowG) {
        return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
    }

    _getCachedCompiledPatterns(grammar) {
        if (!this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns = new RegExpSourceList();
            this.collectPatterns(grammar, this._cachedCompiledPatterns);
        }
        return this._cachedCompiledPatterns;
    }
};
var BeginEndRule = class extends Rule {
    constructor($location, id, name, contentName, begin, beginCaptures, end, endCaptures, applyEndPatternLast, patterns) {
        super($location, id, name, contentName);
        __publicField(this, "_begin");
        __publicField(this, "beginCaptures");
        __publicField(this, "_end");
        __publicField(this, "endHasBackReferences");
        __publicField(this, "endCaptures");
        __publicField(this, "applyEndPatternLast");
        __publicField(this, "hasMissingPatterns");
        __publicField(this, "patterns");
        __publicField(this, "_cachedCompiledPatterns");
        this._begin = new RegExpSource(begin, this.id);
        this.beginCaptures = beginCaptures;
        this._end = new RegExpSource(end ? end : "￿", -1);
        this.endHasBackReferences = this._end.hasBackReferences;
        this.endCaptures = endCaptures;
        this.applyEndPatternLast = applyEndPatternLast || false;
        this.patterns = patterns.patterns;
        this.hasMissingPatterns = patterns.hasMissingPatterns;
        this._cachedCompiledPatterns = null;
    }

    get debugBeginRegExp() {
        return "".concat(this._begin.source);
    }

    get debugEndRegExp() {
        return "".concat(this._end.source);
    }

    dispose() {
        if (this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns.dispose();
            this._cachedCompiledPatterns = null;
        }
    }

    getEndWithResolvedBackReferences(lineText, captureIndices) {
        return this._end.resolveBackReferences(lineText, captureIndices);
    }

    collectPatterns(grammar, out) {
        out.push(this._begin);
    }

    compile(grammar, endRegexSource) {
        return this._getCachedCompiledPatterns(grammar, endRegexSource).compile(grammar);
    }

    compileAG(grammar, endRegexSource, allowA, allowG) {
        return this._getCachedCompiledPatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);
    }

    _getCachedCompiledPatterns(grammar, endRegexSource) {
        if (!this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns = new RegExpSourceList();
            for (const pattern of this.patterns) {
                const rule = grammar.getRule(pattern);
                rule.collectPatterns(grammar, this._cachedCompiledPatterns);
            }
            if (this.applyEndPatternLast) {
                this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end);
            } else {
                this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end);
            }
        }
        if (this._end.hasBackReferences) {
            if (this.applyEndPatternLast) {
                this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, endRegexSource);
            } else {
                this._cachedCompiledPatterns.setSource(0, endRegexSource);
            }
        }
        return this._cachedCompiledPatterns;
    }
};
var BeginWhileRule = class extends Rule {
    constructor($location, id, name, contentName, begin, beginCaptures, _while, whileCaptures, patterns) {
        super($location, id, name, contentName);
        __publicField(this, "_begin");
        __publicField(this, "beginCaptures");
        __publicField(this, "whileCaptures");
        __publicField(this, "_while");
        __publicField(this, "whileHasBackReferences");
        __publicField(this, "hasMissingPatterns");
        __publicField(this, "patterns");
        __publicField(this, "_cachedCompiledPatterns");
        __publicField(this, "_cachedCompiledWhilePatterns");
        this._begin = new RegExpSource(begin, this.id);
        this.beginCaptures = beginCaptures;
        this.whileCaptures = whileCaptures;
        this._while = new RegExpSource(_while, whileRuleId);
        this.whileHasBackReferences = this._while.hasBackReferences;
        this.patterns = patterns.patterns;
        this.hasMissingPatterns = patterns.hasMissingPatterns;
        this._cachedCompiledPatterns = null;
        this._cachedCompiledWhilePatterns = null;
    }

    get debugBeginRegExp() {
        return "".concat(this._begin.source);
    }

    get debugWhileRegExp() {
        return "".concat(this._while.source);
    }

    dispose() {
        if (this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns.dispose();
            this._cachedCompiledPatterns = null;
        }
        if (this._cachedCompiledWhilePatterns) {
            this._cachedCompiledWhilePatterns.dispose();
            this._cachedCompiledWhilePatterns = null;
        }
    }

    getWhileWithResolvedBackReferences(lineText, captureIndices) {
        return this._while.resolveBackReferences(lineText, captureIndices);
    }

    collectPatterns(grammar, out) {
        out.push(this._begin);
    }

    compile(grammar, endRegexSource) {
        return this._getCachedCompiledPatterns(grammar).compile(grammar);
    }

    compileAG(grammar, endRegexSource, allowA, allowG) {
        return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);
    }

    _getCachedCompiledPatterns(grammar) {
        if (!this._cachedCompiledPatterns) {
            this._cachedCompiledPatterns = new RegExpSourceList();
            for (const pattern of this.patterns) {
                const rule = grammar.getRule(pattern);
                rule.collectPatterns(grammar, this._cachedCompiledPatterns);
            }
        }
        return this._cachedCompiledPatterns;
    }

    compileWhile(grammar, endRegexSource) {
        return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compile(grammar);
    }

    compileWhileAG(grammar, endRegexSource, allowA, allowG) {
        return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);
    }

    _getCachedCompiledWhilePatterns(grammar, endRegexSource) {
        if (!this._cachedCompiledWhilePatterns) {
            this._cachedCompiledWhilePatterns = new RegExpSourceList();
            this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while);
        }
        if (this._while.hasBackReferences) {
            this._cachedCompiledWhilePatterns.setSource(0, endRegexSource ? endRegexSource : "￿");
        }
        return this._cachedCompiledWhilePatterns;
    }
};
var RuleFactory = class _RuleFactory {
    static createCaptureRule(helper, $location, name, contentName, retokenizeCapturedWithRuleId) {
        return helper.registerRule((id) => {
            return new CaptureRule($location, id, name, contentName, retokenizeCapturedWithRuleId);
        });
    }

    static getCompiledRuleId(desc, helper, repository) {
        if (!desc.id) {
            helper.registerRule((id) => {
                desc.id = id;
                if (desc.match) {
                    return new MatchRule(
                        desc.$vscodeTextmateLocation,
                        desc.id,
                        desc.name,
                        desc.match,
                        _RuleFactory._compileCaptures(desc.captures, helper, repository)
                    );
                }
                if (typeof desc.begin === "undefined") {
                    if (desc.repository) {
                        repository = mergeObjects({}, repository, desc.repository);
                    }
                    let patterns = desc.patterns;
                    if (typeof patterns === "undefined" && desc.include) {
                        patterns = [{include: desc.include}];
                    }
                    return new IncludeOnlyRule(
                        desc.$vscodeTextmateLocation,
                        desc.id,
                        desc.name,
                        desc.contentName,
                        _RuleFactory._compilePatterns(patterns, helper, repository)
                    );
                }
                if (desc.while) {
                    return new BeginWhileRule(
                        desc.$vscodeTextmateLocation,
                        desc.id,
                        desc.name,
                        desc.contentName,
                        desc.begin,
                        _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),
                        desc.while,
                        _RuleFactory._compileCaptures(desc.whileCaptures || desc.captures, helper, repository),
                        _RuleFactory._compilePatterns(desc.patterns, helper, repository)
                    );
                }
                return new BeginEndRule(
                    desc.$vscodeTextmateLocation,
                    desc.id,
                    desc.name,
                    desc.contentName,
                    desc.begin,
                    _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),
                    desc.end,
                    _RuleFactory._compileCaptures(desc.endCaptures || desc.captures, helper, repository),
                    desc.applyEndPatternLast,
                    _RuleFactory._compilePatterns(desc.patterns, helper, repository)
                );
            });
        }
        return desc.id;
    }

    static _compileCaptures(captures, helper, repository) {
        let r = [];
        if (captures) {
            let maximumCaptureId = 0;
            for (const captureId in captures) {
                if (captureId === "$vscodeTextmateLocation") {
                    continue;
                }
                const numericCaptureId = parseInt(captureId, 10);
                if (numericCaptureId > maximumCaptureId) {
                    maximumCaptureId = numericCaptureId;
                }
            }
            for (let i = 0; i <= maximumCaptureId; i++) {
                r[i] = null;
            }
            for (const captureId in captures) {
                if (captureId === "$vscodeTextmateLocation") {
                    continue;
                }
                const numericCaptureId = parseInt(captureId, 10);
                let retokenizeCapturedWithRuleId = 0;
                if (captures[captureId].patterns) {
                    retokenizeCapturedWithRuleId = _RuleFactory.getCompiledRuleId(captures[captureId], helper, repository);
                }
                r[numericCaptureId] = _RuleFactory.createCaptureRule(helper, captures[captureId].$vscodeTextmateLocation, captures[captureId].name, captures[captureId].contentName, retokenizeCapturedWithRuleId);
            }
        }
        return r;
    }

    static _compilePatterns(patterns, helper, repository) {
        let r = [];
        if (patterns) {
            for (let i = 0, len = patterns.length; i < len; i++) {
                const pattern = patterns[i];
                let ruleId = -1;
                if (pattern.include) {
                    const reference = parseInclude(pattern.include);
                    switch (reference.kind) {
                        case 0:
                        case 1:
                            ruleId = _RuleFactory.getCompiledRuleId(repository[pattern.include], helper, repository);
                            break;
                        case 2:
                            let localIncludedRule = repository[reference.ruleName];
                            if (localIncludedRule) {
                                ruleId = _RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository);
                            }
                            break;
                        case 3:
                        case 4:
                            const externalGrammarName = reference.scopeName;
                            const externalGrammarInclude = reference.kind === 4 ? reference.ruleName : null;
                            const externalGrammar = helper.getExternalGrammar(externalGrammarName, repository);
                            if (externalGrammar) {
                                if (externalGrammarInclude) {
                                    let externalIncludedRule = externalGrammar.repository[externalGrammarInclude];
                                    if (externalIncludedRule) {
                                        ruleId = _RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository);
                                    }
                                } else {
                                    ruleId = _RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository);
                                }
                            }
                            break;
                    }
                } else {
                    ruleId = _RuleFactory.getCompiledRuleId(pattern, helper, repository);
                }
                if (ruleId !== -1) {
                    const rule = helper.getRule(ruleId);
                    let skipRule = false;
                    if (rule instanceof IncludeOnlyRule || rule instanceof BeginEndRule || rule instanceof BeginWhileRule) {
                        if (rule.hasMissingPatterns && rule.patterns.length === 0) {
                            skipRule = true;
                        }
                    }
                    if (skipRule) {
                        continue;
                    }
                    r.push(ruleId);
                }
            }
        }
        return {
            patterns: r,
            hasMissingPatterns: (patterns ? patterns.length : 0) !== r.length
        };
    }
};
var RegExpSource = class _RegExpSource {
    constructor(regExpSource, ruleId) {
        __publicField(this, "source");
        __publicField(this, "ruleId");
        __publicField(this, "hasAnchor");
        __publicField(this, "hasBackReferences");
        __publicField(this, "_anchorCache");
        if (regExpSource && typeof regExpSource === "string") {
            const len = regExpSource.length;
            let lastPushedPos = 0;
            let output = [];
            let hasAnchor = false;
            for (let pos = 0; pos < len; pos++) {
                const ch = regExpSource.charAt(pos);
                if (ch === "\\") {
                    if (pos + 1 < len) {
                        const nextCh = regExpSource.charAt(pos + 1);
                        if (nextCh === "z") {
                            output.push(regExpSource.substring(lastPushedPos, pos));
                            output.push("$(?!\\n)(?<!\\n)");
                            lastPushedPos = pos + 2;
                        } else if (nextCh === "A" || nextCh === "G") {
                            hasAnchor = true;
                        }
                        pos++;
                    }
                }
            }
            this.hasAnchor = hasAnchor;
            if (lastPushedPos === 0) {
                this.source = regExpSource;
            } else {
                output.push(regExpSource.substring(lastPushedPos, len));
                this.source = output.join("");
            }
        } else {
            this.hasAnchor = false;
            this.source = regExpSource;
        }
        if (this.hasAnchor) {
            this._anchorCache = this._buildAnchorCache();
        } else {
            this._anchorCache = null;
        }
        this.ruleId = ruleId;
        if (typeof this.source === "string") {
            this.hasBackReferences = HAS_BACK_REFERENCES.test(this.source);
        } else {
            this.hasBackReferences = false;
        }
    }

    clone() {
        return new _RegExpSource(this.source, this.ruleId);
    }

    setSource(newSource) {
        if (this.source === newSource) {
            return;
        }
        this.source = newSource;
        if (this.hasAnchor) {
            this._anchorCache = this._buildAnchorCache();
        }
    }

    resolveBackReferences(lineText, captureIndices) {
        if (typeof this.source !== "string") {
            throw new Error("This method should only be called if the source is a string");
        }
        let capturedValues = captureIndices.map((capture) => {
            return lineText.substring(capture.start, capture.end);
        });
        BACK_REFERENCING_END.lastIndex = 0;
        return this.source.replace(BACK_REFERENCING_END, (match, g1) => {
            return escapeRegExpCharacters(capturedValues[parseInt(g1, 10)] || "");
        });
    }

    _buildAnchorCache() {
        if (typeof this.source !== "string") {
            throw new Error("This method should only be called if the source is a string");
        }
        let A0_G0_result = [];
        let A0_G1_result = [];
        let A1_G0_result = [];
        let A1_G1_result = [];
        let pos, len, ch, nextCh;
        for (pos = 0, len = this.source.length; pos < len; pos++) {
            ch = this.source.charAt(pos);
            A0_G0_result[pos] = ch;
            A0_G1_result[pos] = ch;
            A1_G0_result[pos] = ch;
            A1_G1_result[pos] = ch;
            if (ch === "\\") {
                if (pos + 1 < len) {
                    nextCh = this.source.charAt(pos + 1);
                    if (nextCh === "A") {
                        A0_G0_result[pos + 1] = "￿";
                        A0_G1_result[pos + 1] = "￿";
                        A1_G0_result[pos + 1] = "A";
                        A1_G1_result[pos + 1] = "A";
                    } else if (nextCh === "G") {
                        A0_G0_result[pos + 1] = "￿";
                        A0_G1_result[pos + 1] = "G";
                        A1_G0_result[pos + 1] = "￿";
                        A1_G1_result[pos + 1] = "G";
                    } else {
                        A0_G0_result[pos + 1] = nextCh;
                        A0_G1_result[pos + 1] = nextCh;
                        A1_G0_result[pos + 1] = nextCh;
                        A1_G1_result[pos + 1] = nextCh;
                    }
                    pos++;
                }
            }
        }
        return {
            A0_G0: A0_G0_result.join(""),
            A0_G1: A0_G1_result.join(""),
            A1_G0: A1_G0_result.join(""),
            A1_G1: A1_G1_result.join("")
        };
    }

    resolveAnchors(allowA, allowG) {
        if (!this.hasAnchor || !this._anchorCache || typeof this.source !== "string") {
            return this.source;
        }
        if (allowA) {
            if (allowG) {
                return this._anchorCache.A1_G1;
            } else {
                return this._anchorCache.A1_G0;
            }
        } else {
            if (allowG) {
                return this._anchorCache.A0_G1;
            } else {
                return this._anchorCache.A0_G0;
            }
        }
    }
};
var RegExpSourceList = class {
    constructor() {
        __publicField(this, "_items");
        __publicField(this, "_hasAnchors");
        __publicField(this, "_cached");
        __publicField(this, "_anchorCache");
        this._items = [];
        this._hasAnchors = false;
        this._cached = null;
        this._anchorCache = {
            A0_G0: null,
            A0_G1: null,
            A1_G0: null,
            A1_G1: null
        };
    }

    dispose() {
        this._disposeCaches();
    }

    _disposeCaches() {
        if (this._cached) {
            this._cached.dispose();
            this._cached = null;
        }
        if (this._anchorCache.A0_G0) {
            this._anchorCache.A0_G0.dispose();
            this._anchorCache.A0_G0 = null;
        }
        if (this._anchorCache.A0_G1) {
            this._anchorCache.A0_G1.dispose();
            this._anchorCache.A0_G1 = null;
        }
        if (this._anchorCache.A1_G0) {
            this._anchorCache.A1_G0.dispose();
            this._anchorCache.A1_G0 = null;
        }
        if (this._anchorCache.A1_G1) {
            this._anchorCache.A1_G1.dispose();
            this._anchorCache.A1_G1 = null;
        }
    }

    push(item) {
        this._items.push(item);
        this._hasAnchors = this._hasAnchors || item.hasAnchor;
    }

    unshift(item) {
        this._items.unshift(item);
        this._hasAnchors = this._hasAnchors || item.hasAnchor;
    }

    length() {
        return this._items.length;
    }

    setSource(index, newSource) {
        if (this._items[index].source !== newSource) {
            this._disposeCaches();
            this._items[index].setSource(newSource);
        }
    }

    compile(onigLib) {
        if (!this._cached) {
            let regExps = this._items.map((e) => e.source);
            this._cached = new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));
        }
        return this._cached;
    }

    compileAG(onigLib, allowA, allowG) {
        if (!this._hasAnchors) {
            return this.compile(onigLib);
        } else {
            if (allowA) {
                if (allowG) {
                    if (!this._anchorCache.A1_G1) {
                        this._anchorCache.A1_G1 = this._resolveAnchors(onigLib, allowA, allowG);
                    }
                    return this._anchorCache.A1_G1;
                } else {
                    if (!this._anchorCache.A1_G0) {
                        this._anchorCache.A1_G0 = this._resolveAnchors(onigLib, allowA, allowG);
                    }
                    return this._anchorCache.A1_G0;
                }
            } else {
                if (allowG) {
                    if (!this._anchorCache.A0_G1) {
                        this._anchorCache.A0_G1 = this._resolveAnchors(onigLib, allowA, allowG);
                    }
                    return this._anchorCache.A0_G1;
                } else {
                    if (!this._anchorCache.A0_G0) {
                        this._anchorCache.A0_G0 = this._resolveAnchors(onigLib, allowA, allowG);
                    }
                    return this._anchorCache.A0_G0;
                }
            }
        }
    }

    _resolveAnchors(onigLib, allowA, allowG) {
        let regExps = this._items.map((e) => e.resolveAnchors(allowA, allowG));
        return new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));
    }
};
var CompiledRule = class {
    constructor(onigLib, regExps, rules) {
        __publicField(this, "scanner");
        this.regExps = regExps;
        this.rules = rules;
        this.scanner = onigLib.createOnigScanner(regExps);
    }

    dispose() {
        if (typeof this.scanner.dispose === "function") {
            this.scanner.dispose();
        }
    }

    toString() {
        const r = [];
        for (let i = 0, len = this.rules.length; i < len; i++) {
            r.push("   - " + this.rules[i] + ": " + this.regExps[i]);
        }
        return r.join("\n");
    }

    findNextMatchSync(string, startPosition, options) {
        const result = this.scanner.findNextMatchSync(string, startPosition, options);
        if (!result) {
            return null;
        }
        return {
            ruleId: this.rules[result.index],
            captureIndices: result.captureIndices
        };
    }
};
var BasicScopeAttributes = class {
    constructor(languageId, tokenType) {
        this.languageId = languageId;
        this.tokenType = tokenType;
    }
};
var BasicScopeAttributesProvider = (_a = class {
    constructor(initialLanguageId, embeddedLanguages) {
        __publicField(this, "_defaultAttributes");
        __publicField(this, "_embeddedLanguagesMatcher");
        __publicField(this, "_getBasicScopeAttributes", new CachedFn((scopeName) => {
            const languageId = this._scopeToLanguage(scopeName);
            const standardTokenType = this._toStandardTokenType(scopeName);
            return new BasicScopeAttributes(languageId, standardTokenType);
        }));
        this._defaultAttributes = new BasicScopeAttributes(
            initialLanguageId,
            8
            /* NotSet */
        );
        this._embeddedLanguagesMatcher = new ScopeMatcher(Object.entries(embeddedLanguages || {}));
    }

    getDefaultAttributes() {
        return this._defaultAttributes;
    }

    getBasicScopeAttributes(scopeName) {
        if (scopeName === null) {
            return _a._NULL_SCOPE_METADATA;
        }
        return this._getBasicScopeAttributes.get(scopeName);
    }

    /**
     * Given a produced TM scope, return the language that token describes or null if unknown.
     * e.g. source.html => html, source.css.embedded.html => css, punctuation.definition.tag.html => null
     */
    _scopeToLanguage(scope) {
        return this._embeddedLanguagesMatcher.match(scope) || 0;
    }

    _toStandardTokenType(scopeName) {
        const m = scopeName.match(_a.STANDARD_TOKEN_TYPE_REGEXP);
        if (!m) {
            return 8;
        }
        switch (m[1]) {
            case "comment":
                return 1;
            case "string":
                return 2;
            case "regex":
                return 3;
            case "meta.embedded":
                return 0;
        }
        throw new Error("Unexpected match for standard token type!");
    }
}, __publicField(_a, "_NULL_SCOPE_METADATA", new BasicScopeAttributes(0, 0)), __publicField(_a, "STANDARD_TOKEN_TYPE_REGEXP", /\b(comment|string|regex|meta\.embedded)\b/), _a);
var ScopeMatcher = class {
    constructor(values) {
        __publicField(this, "values");
        __publicField(this, "scopesRegExp");
        if (values.length === 0) {
            this.values = null;
            this.scopesRegExp = null;
        } else {
            this.values = new Map(values);
            const escapedScopes = values.map(
                ([scopeName, value]) => escapeRegExpCharacters(scopeName)
            );
            escapedScopes.sort();
            escapedScopes.reverse();
            this.scopesRegExp = new RegExp(
                "^((".concat(escapedScopes.join(")|("), "))($|\\.)"),
                ""
            );
        }
    }

    match(scope) {
        if (!this.scopesRegExp) {
            return void 0;
        }
        const m = scope.match(this.scopesRegExp);
        if (!m) {
            return void 0;
        }
        return this.values.get(m[1]);
    }
};
var TokenizeStringResult = class {
    constructor(stack, stoppedEarly) {
        this.stack = stack;
        this.stoppedEarly = stoppedEarly;
    }
};

function _tokenizeString(grammar, lineText, isFirstLine, linePos, stack, lineTokens, checkWhileConditions, timeLimit) {
    const lineLength = lineText.content.length;
    let STOP = false;
    let anchorPosition = -1;
    if (checkWhileConditions) {
        const whileCheckResult = _checkWhileConditions(
            grammar,
            lineText,
            isFirstLine,
            linePos,
            stack,
            lineTokens
        );
        stack = whileCheckResult.stack;
        linePos = whileCheckResult.linePos;
        isFirstLine = whileCheckResult.isFirstLine;
        anchorPosition = whileCheckResult.anchorPosition;
    }
    const startTime = Date.now();
    while (!STOP) {
        if (timeLimit !== 0) {
            const elapsedTime = Date.now() - startTime;
            if (elapsedTime > timeLimit) {
                return new TokenizeStringResult(stack, true);
            }
        }
        scanNext();
    }
    return new TokenizeStringResult(stack, false);

    function scanNext() {
        const r = matchRuleOrInjections(
            grammar,
            lineText,
            isFirstLine,
            linePos,
            stack,
            anchorPosition
        );
        if (!r) {
            lineTokens.produce(stack, lineLength);
            STOP = true;
            return;
        }
        const captureIndices = r.captureIndices;
        const matchedRuleId = r.matchedRuleId;
        const hasAdvanced = captureIndices && captureIndices.length > 0 ? captureIndices[0].end > linePos : false;
        if (matchedRuleId === endRuleId) {
            const poppedRule = stack.getRule(grammar);
            lineTokens.produce(stack, captureIndices[0].start);
            stack = stack.withContentNameScopesList(stack.nameScopesList);
            handleCaptures(
                grammar,
                lineText,
                isFirstLine,
                stack,
                lineTokens,
                poppedRule.endCaptures,
                captureIndices
            );
            lineTokens.produce(stack, captureIndices[0].end);
            const popped = stack;
            stack = stack.parent;
            anchorPosition = popped.getAnchorPos();
            if (!hasAdvanced && popped.getEnterPos() === linePos) {
                stack = popped;
                lineTokens.produce(stack, lineLength);
                STOP = true;
                return;
            }
        } else {
            const _rule = grammar.getRule(matchedRuleId);
            lineTokens.produce(stack, captureIndices[0].start);
            const beforePush = stack;
            const scopeName = _rule.getName(lineText.content, captureIndices);
            const nameScopesList = stack.contentNameScopesList.pushAttributed(
                scopeName,
                grammar
            );
            stack = stack.push(
                matchedRuleId,
                linePos,
                anchorPosition,
                captureIndices[0].end === lineLength,
                null,
                nameScopesList,
                nameScopesList
            );
            if (_rule instanceof BeginEndRule) {
                const pushedRule = _rule;
                handleCaptures(
                    grammar,
                    lineText,
                    isFirstLine,
                    stack,
                    lineTokens,
                    pushedRule.beginCaptures,
                    captureIndices
                );
                lineTokens.produce(stack, captureIndices[0].end);
                anchorPosition = captureIndices[0].end;
                const contentName = pushedRule.getContentName(
                    lineText.content,
                    captureIndices
                );
                const contentNameScopesList = nameScopesList.pushAttributed(
                    contentName,
                    grammar
                );
                stack = stack.withContentNameScopesList(contentNameScopesList);
                if (pushedRule.endHasBackReferences) {
                    stack = stack.withEndRule(
                        pushedRule.getEndWithResolvedBackReferences(
                            lineText.content,
                            captureIndices
                        )
                    );
                }
                if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
                    stack = stack.pop();
                    lineTokens.produce(stack, lineLength);
                    STOP = true;
                    return;
                }
            } else if (_rule instanceof BeginWhileRule) {
                const pushedRule = _rule;
                handleCaptures(
                    grammar,
                    lineText,
                    isFirstLine,
                    stack,
                    lineTokens,
                    pushedRule.beginCaptures,
                    captureIndices
                );
                lineTokens.produce(stack, captureIndices[0].end);
                anchorPosition = captureIndices[0].end;
                const contentName = pushedRule.getContentName(
                    lineText.content,
                    captureIndices
                );
                const contentNameScopesList = nameScopesList.pushAttributed(
                    contentName,
                    grammar
                );
                stack = stack.withContentNameScopesList(contentNameScopesList);
                if (pushedRule.whileHasBackReferences) {
                    stack = stack.withEndRule(
                        pushedRule.getWhileWithResolvedBackReferences(
                            lineText.content,
                            captureIndices
                        )
                    );
                }
                if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {
                    stack = stack.pop();
                    lineTokens.produce(stack, lineLength);
                    STOP = true;
                    return;
                }
            } else {
                const matchingRule = _rule;
                handleCaptures(
                    grammar,
                    lineText,
                    isFirstLine,
                    stack,
                    lineTokens,
                    matchingRule.captures,
                    captureIndices
                );
                lineTokens.produce(stack, captureIndices[0].end);
                stack = stack.pop();
                if (!hasAdvanced) {
                    stack = stack.safePop();
                    lineTokens.produce(stack, lineLength);
                    STOP = true;
                    return;
                }
            }
        }
        if (captureIndices[0].end > linePos) {
            linePos = captureIndices[0].end;
            isFirstLine = false;
        }
    }
}

function _checkWhileConditions(grammar, lineText, isFirstLine, linePos, stack, lineTokens) {
    let anchorPosition = stack.beginRuleCapturedEOL ? 0 : -1;
    const whileRules = [];
    for (let node = stack; node; node = node.pop()) {
        const nodeRule = node.getRule(grammar);
        if (nodeRule instanceof BeginWhileRule) {
            whileRules.push({
                rule: nodeRule,
                stack: node
            });
        }
    }
    for (let whileRule = whileRules.pop(); whileRule; whileRule = whileRules.pop()) {
        const {
            ruleScanner,
            findOptions
        } = prepareRuleWhileSearch(whileRule.rule, grammar, whileRule.stack.endRule, isFirstLine, linePos === anchorPosition);
        const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
        if (r) {
            const matchedRuleId = r.ruleId;
            if (matchedRuleId !== whileRuleId) {
                stack = whileRule.stack.pop();
                break;
            }
            if (r.captureIndices && r.captureIndices.length) {
                lineTokens.produce(whileRule.stack, r.captureIndices[0].start);
                handleCaptures(grammar, lineText, isFirstLine, whileRule.stack, lineTokens, whileRule.rule.whileCaptures, r.captureIndices);
                lineTokens.produce(whileRule.stack, r.captureIndices[0].end);
                anchorPosition = r.captureIndices[0].end;
                if (r.captureIndices[0].end > linePos) {
                    linePos = r.captureIndices[0].end;
                    isFirstLine = false;
                }
            }
        } else {
            stack = whileRule.stack.pop();
            break;
        }
    }
    return {stack, linePos, anchorPosition, isFirstLine};
}

function matchRuleOrInjections(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
    const matchResult = matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition);
    const injections = grammar.getInjections();
    if (injections.length === 0) {
        return matchResult;
    }
    const injectionResult = matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition);
    if (!injectionResult) {
        return matchResult;
    }
    if (!matchResult) {
        return injectionResult;
    }
    const matchResultScore = matchResult.captureIndices[0].start;
    const injectionResultScore = injectionResult.captureIndices[0].start;
    if (injectionResultScore < matchResultScore || injectionResult.priorityMatch && injectionResultScore === matchResultScore) {
        return injectionResult;
    }
    return matchResult;
}

function matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
    const rule = stack.getRule(grammar);
    const {
        ruleScanner,
        findOptions
    } = prepareRuleSearch(rule, grammar, stack.endRule, isFirstLine, linePos === anchorPosition);
    const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
    if (r) {
        return {
            captureIndices: r.captureIndices,
            matchedRuleId: r.ruleId
        };
    }
    return null;
}

function matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {
    let bestMatchRating = Number.MAX_VALUE;
    let bestMatchCaptureIndices = null;
    let bestMatchRuleId;
    let bestMatchResultPriority = 0;
    const scopes = stack.contentNameScopesList.getScopeNames();
    for (let i = 0, len = injections.length; i < len; i++) {
        const injection = injections[i];
        if (!injection.matcher(scopes)) {
            continue;
        }
        const rule = grammar.getRule(injection.ruleId);
        const {
            ruleScanner,
            findOptions
        } = prepareRuleSearch(rule, grammar, null, isFirstLine, linePos === anchorPosition);
        const matchResult = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);
        if (!matchResult) {
            continue;
        }
        const matchRating = matchResult.captureIndices[0].start;
        if (matchRating >= bestMatchRating) {
            continue;
        }
        bestMatchRating = matchRating;
        bestMatchCaptureIndices = matchResult.captureIndices;
        bestMatchRuleId = matchResult.ruleId;
        bestMatchResultPriority = injection.priority;
        if (bestMatchRating === linePos) {
            break;
        }
    }
    if (bestMatchCaptureIndices) {
        return {
            priorityMatch: bestMatchResultPriority === -1,
            captureIndices: bestMatchCaptureIndices,
            matchedRuleId: bestMatchRuleId
        };
    }
    return null;
}

function prepareRuleSearch(rule, grammar, endRegexSource, allowA, allowG) {
    const ruleScanner = rule.compileAG(grammar, endRegexSource, allowA, allowG);
    return {
        ruleScanner,
        findOptions: 0
        /* None */
    };
}

function prepareRuleWhileSearch(rule, grammar, endRegexSource, allowA, allowG) {
    const ruleScanner = rule.compileWhileAG(grammar, endRegexSource, allowA, allowG);
    return {
        ruleScanner,
        findOptions: 0
        /* None */
    };
}

function handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, captures, captureIndices) {
    if (captures.length === 0) {
        return;
    }
    const lineTextContent = lineText.content;
    const len = Math.min(captures.length, captureIndices.length);
    const localStack = [];
    const maxEnd = captureIndices[0].end;
    for (let i = 0; i < len; i++) {
        const captureRule = captures[i];
        if (captureRule === null) {
            continue;
        }
        const captureIndex = captureIndices[i];
        if (captureIndex.length === 0) {
            continue;
        }
        if (captureIndex.start > maxEnd) {
            break;
        }
        while (localStack.length > 0 && localStack[localStack.length - 1].endPos <= captureIndex.start) {
            lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);
            localStack.pop();
        }
        if (localStack.length > 0) {
            lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, captureIndex.start);
        } else {
            lineTokens.produce(stack, captureIndex.start);
        }
        if (captureRule.retokenizeCapturedWithRuleId) {
            const scopeName = captureRule.getName(lineTextContent, captureIndices);
            const nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar);
            const contentName = captureRule.getContentName(lineTextContent, captureIndices);
            const contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar);
            const stackClone = stack.push(captureRule.retokenizeCapturedWithRuleId, captureIndex.start, -1, false, null, nameScopesList, contentNameScopesList);
            const onigSubStr = grammar.createOnigString(lineTextContent.substring(0, captureIndex.end));
            _tokenizeString(
                grammar,
                onigSubStr,
                isFirstLine && captureIndex.start === 0,
                captureIndex.start,
                stackClone,
                lineTokens,
                false,
                /* no time limit */
                0
            );
            disposeOnigString(onigSubStr);
            continue;
        }
        const captureRuleScopeName = captureRule.getName(lineTextContent, captureIndices);
        if (captureRuleScopeName !== null) {
            const base = localStack.length > 0 ? localStack[localStack.length - 1].scopes : stack.contentNameScopesList;
            const captureRuleScopesList = base.pushAttributed(captureRuleScopeName, grammar);
            localStack.push(new LocalStackElement(captureRuleScopesList, captureIndex.end));
        }
    }
    while (localStack.length > 0) {
        lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);
        localStack.pop();
    }
}

var LocalStackElement = class {
    constructor(scopes, endPos) {
        __publicField(this, "scopes");
        __publicField(this, "endPos");
        this.scopes = scopes;
        this.endPos = endPos;
    }
};

function createGrammar(scopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, onigLib) {
    return new Grammar(
        scopeName,
        grammar,
        initialLanguage,
        embeddedLanguages,
        tokenTypes,
        balancedBracketSelectors,
        grammarRepository,
        onigLib
    );
}

function collectInjections(result, selector, rule, ruleFactoryHelper, grammar) {
    const matchers = createMatchers(selector, nameMatcher);
    const ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);
    for (const matcher of matchers) {
        result.push({
            debugSelector: selector,
            matcher: matcher.matcher,
            ruleId,
            grammar,
            priority: matcher.priority
        });
    }
}

function nameMatcher(identifers, scopes) {
    if (scopes.length < identifers.length) {
        return false;
    }
    let lastIndex = 0;
    return identifers.every((identifier) => {
        for (let i = lastIndex; i < scopes.length; i++) {
            if (scopesAreMatching(scopes[i], identifier)) {
                lastIndex = i + 1;
                return true;
            }
        }
        return false;
    });
}

function scopesAreMatching(thisScopeName, scopeName) {
    if (!thisScopeName) {
        return false;
    }
    if (thisScopeName === scopeName) {
        return true;
    }
    const len = scopeName.length;
    return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === ".";
}

var Grammar = class {
    constructor(_rootScopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, _onigLib) {
        __publicField(this, "_rootId");
        __publicField(this, "_lastRuleId");
        __publicField(this, "_ruleId2desc");
        __publicField(this, "_includedGrammars");
        __publicField(this, "_grammarRepository");
        __publicField(this, "_grammar");
        __publicField(this, "_injections");
        __publicField(this, "_basicScopeAttributesProvider");
        __publicField(this, "_tokenTypeMatchers");
        this._rootScopeName = _rootScopeName;
        this.balancedBracketSelectors = balancedBracketSelectors;
        this._onigLib = _onigLib;
        this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(
            initialLanguage,
            embeddedLanguages
        );
        this._rootId = -1;
        this._lastRuleId = 0;
        this._ruleId2desc = [null];
        this._includedGrammars = {};
        this._grammarRepository = grammarRepository;
        this._grammar = initGrammar(grammar, null);
        this._injections = null;
        this._tokenTypeMatchers = [];
        if (tokenTypes) {
            for (const selector of Object.keys(tokenTypes)) {
                const matchers = createMatchers(selector, nameMatcher);
                for (const matcher of matchers) {
                    this._tokenTypeMatchers.push({
                        matcher: matcher.matcher,
                        type: tokenTypes[selector]
                    });
                }
            }
        }
    }

    get themeProvider() {
        return this._grammarRepository;
    }

    dispose() {
        for (const rule of this._ruleId2desc) {
            if (rule) {
                rule.dispose();
            }
        }
    }

    createOnigScanner(sources) {
        return this._onigLib.createOnigScanner(sources);
    }

    createOnigString(sources) {
        return this._onigLib.createOnigString(sources);
    }

    getMetadataForScope(scope) {
        return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);
    }

    _collectInjections() {
        const grammarRepository = {
            lookup: (scopeName2) => {
                if (scopeName2 === this._rootScopeName) {
                    return this._grammar;
                }
                return this.getExternalGrammar(scopeName2);
            },
            injections: (scopeName2) => {
                return this._grammarRepository.injections(scopeName2);
            }
        };
        const result = [];
        const scopeName = this._rootScopeName;
        const grammar = grammarRepository.lookup(scopeName);
        if (grammar) {
            const rawInjections = grammar.injections;
            if (rawInjections) {
                for (let expression in rawInjections) {
                    collectInjections(
                        result,
                        expression,
                        rawInjections[expression],
                        this,
                        grammar
                    );
                }
            }
            const injectionScopeNames = this._grammarRepository.injections(scopeName);
            if (injectionScopeNames) {
                injectionScopeNames.forEach((injectionScopeName) => {
                    const injectionGrammar = this.getExternalGrammar(injectionScopeName);
                    if (injectionGrammar) {
                        const selector = injectionGrammar.injectionSelector;
                        if (selector) {
                            collectInjections(
                                result,
                                selector,
                                injectionGrammar,
                                this,
                                injectionGrammar
                            );
                        }
                    }
                });
            }
        }
        result.sort((i1, i2) => i1.priority - i2.priority);
        return result;
    }

    getInjections() {
        if (this._injections === null) {
            this._injections = this._collectInjections();
        }
        return this._injections;
    }

    registerRule(factory) {
        const id = ++this._lastRuleId;
        const result = factory(ruleIdFromNumber(id));
        this._ruleId2desc[id] = result;
        return result;
    }

    getRule(ruleId) {
        return this._ruleId2desc[ruleIdToNumber(ruleId)];
    }

    getExternalGrammar(scopeName, repository) {
        if (this._includedGrammars[scopeName]) {
            return this._includedGrammars[scopeName];
        } else if (this._grammarRepository) {
            const rawIncludedGrammar = this._grammarRepository.lookup(scopeName);
            if (rawIncludedGrammar) {
                this._includedGrammars[scopeName] = initGrammar(
                    rawIncludedGrammar,
                    repository && repository.$base
                );
                return this._includedGrammars[scopeName];
            }
        }
        return void 0;
    }

    tokenizeLine(lineText, prevState, timeLimit = 0) {
        const r = this._tokenize(lineText, prevState, false, timeLimit);
        return {
            tokens: r.lineTokens.getResult(r.ruleStack, r.lineLength),
            ruleStack: r.ruleStack,
            stoppedEarly: r.stoppedEarly
        };
    }

    tokenizeLine2(lineText, prevState, timeLimit = 0) {
        const r = this._tokenize(lineText, prevState, true, timeLimit);
        return {
            tokens: r.lineTokens.getBinaryResult(r.ruleStack, r.lineLength),
            ruleStack: r.ruleStack,
            stoppedEarly: r.stoppedEarly
        };
    }

    _tokenize(lineText, prevState, emitBinaryTokens, timeLimit) {
        if (this._rootId === -1) {
            this._rootId = RuleFactory.getCompiledRuleId(
                this._grammar.repository.$self,
                this,
                this._grammar.repository
            );
            this.getInjections();
        }
        let isFirstLine;
        if (!prevState || prevState === StateStackImpl.NULL) {
            isFirstLine = true;
            const rawDefaultMetadata = this._basicScopeAttributesProvider.getDefaultAttributes();
            const defaultStyle = this.themeProvider.getDefaults();
            const defaultMetadata = EncodedTokenMetadata.set(
                0,
                rawDefaultMetadata.languageId,
                rawDefaultMetadata.tokenType,
                null,
                defaultStyle.fontStyle,
                defaultStyle.foregroundId,
                defaultStyle.backgroundId
            );
            const rootScopeName = this.getRule(this._rootId).getName(
                null,
                null
            );
            let scopeList;
            if (rootScopeName) {
                scopeList = AttributedScopeStack.createRootAndLookUpScopeName(
                    rootScopeName,
                    defaultMetadata,
                    this
                );
            } else {
                scopeList = AttributedScopeStack.createRoot(
                    "unknown",
                    defaultMetadata
                );
            }
            prevState = new StateStackImpl(
                null,
                this._rootId,
                -1,
                -1,
                false,
                null,
                scopeList,
                scopeList
            );
        } else {
            isFirstLine = false;
            prevState.reset();
        }
        lineText = lineText + "\n";
        const onigLineText = this.createOnigString(lineText);
        const lineLength = onigLineText.content.length;
        const lineTokens = new LineTokens(
            emitBinaryTokens,
            lineText,
            this._tokenTypeMatchers,
            this.balancedBracketSelectors
        );
        const r = _tokenizeString(
            this,
            onigLineText,
            isFirstLine,
            0,
            prevState,
            lineTokens,
            true,
            timeLimit
        );
        disposeOnigString(onigLineText);
        return {
            lineLength,
            lineTokens,
            ruleStack: r.stack,
            stoppedEarly: r.stoppedEarly
        };
    }
};

function initGrammar(grammar, base) {
    grammar = clone(grammar);
    grammar.repository = grammar.repository || {};
    grammar.repository.$self = {
        $vscodeTextmateLocation: grammar.$vscodeTextmateLocation,
        patterns: grammar.patterns,
        name: grammar.scopeName
    };
    grammar.repository.$base = base || grammar.repository.$self;
    return grammar;
}

var AttributedScopeStack = class _AttributedScopeStack {
    /**
     * Invariant:
     * ```
     * if (parent && !scopePath.extends(parent.scopePath)) {
     * 	throw new Error();
     * }
     * ```
     */
    constructor(parent, scopePath, tokenAttributes) {
        this.parent = parent;
        this.scopePath = scopePath;
        this.tokenAttributes = tokenAttributes;
    }

    get scopeName() {
        return this.scopePath.scopeName;
    }

    static fromExtension(namesScopeList, contentNameScopesList) {
        var _a2;
        let current = namesScopeList;
        let scopeNames = (_a2 = namesScopeList == null ? void 0 : namesScopeList.scopePath) != null ? _a2 : null;
        for (const frame of contentNameScopesList) {
            scopeNames = ScopeStack.push(scopeNames, frame.scopeNames);
            current = new _AttributedScopeStack(current, scopeNames, frame.encodedTokenAttributes);
        }
        return current;
    }

    static createRoot(scopeName, tokenAttributes) {
        return new _AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes);
    }

    static createRootAndLookUpScopeName(scopeName, tokenAttributes, grammar) {
        const rawRootMetadata = grammar.getMetadataForScope(scopeName);
        const scopePath = new ScopeStack(null, scopeName);
        const rootStyle = grammar.themeProvider.themeMatch(scopePath);
        const resolvedTokenAttributes = _AttributedScopeStack.mergeAttributes(
            tokenAttributes,
            rawRootMetadata,
            rootStyle
        );
        return new _AttributedScopeStack(null, scopePath, resolvedTokenAttributes);
    }

    static equals(a, b) {
        do {
            if (a === b) {
                return true;
            }
            if (!a && !b) {
                return true;
            }
            if (!a || !b) {
                return false;
            }
            if (a.scopeName !== b.scopeName || a.tokenAttributes !== b.tokenAttributes) {
                return false;
            }
            a = a.parent;
            b = b.parent;
        } while (true);
    }

    static mergeAttributes(existingTokenAttributes, basicScopeAttributes, styleAttributes) {
        let fontStyle = -1;
        let foreground = 0;
        let background = 0;
        if (styleAttributes !== null) {
            fontStyle = styleAttributes.fontStyle;
            foreground = styleAttributes.foregroundId;
            background = styleAttributes.backgroundId;
        }
        return EncodedTokenMetadata.set(
            existingTokenAttributes,
            basicScopeAttributes.languageId,
            basicScopeAttributes.tokenType,
            null,
            fontStyle,
            foreground,
            background
        );
    }

    static _pushAttributed(target, scopeName, grammar) {
        const rawMetadata = grammar.getMetadataForScope(scopeName);
        const newPath = target.scopePath.push(scopeName);
        const scopeThemeMatchResult = grammar.themeProvider.themeMatch(newPath);
        const metadata = _AttributedScopeStack.mergeAttributes(
            target.tokenAttributes,
            rawMetadata,
            scopeThemeMatchResult
        );
        return new _AttributedScopeStack(target, newPath, metadata);
    }

    toString() {
        return this.getScopeNames().join(" ");
    }

    equals(other) {
        return _AttributedScopeStack.equals(this, other);
    }

    pushAttributed(scopePath, grammar) {
        if (scopePath === null) {
            return this;
        }
        if (scopePath.indexOf(" ") === -1) {
            return _AttributedScopeStack._pushAttributed(this, scopePath, grammar);
        }
        const scopes = scopePath.split(/ /g);
        let result = this;
        for (const scope of scopes) {
            result = _AttributedScopeStack._pushAttributed(result, scope, grammar);
        }
        return result;
    }

    getScopeNames() {
        return this.scopePath.getSegments();
    }

    getExtensionIfDefined(base) {
        var _a2, _b2;
        const result = [];
        let self = this;
        while (self && self !== base) {
            result.push({
                encodedTokenAttributes: self.tokenAttributes,
                scopeNames: self.scopePath.getExtensionIfDefined((_b2 = (_a2 = self.parent) == null ? void 0 : _a2.scopePath) != null ? _b2 : null)
            });
            self = self.parent;
        }
        return self === base ? result.reverse() : void 0;
    }
};
var StateStackImpl = (_b = class {
    /**
     * Invariant:
     * ```
     * if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {
     * 	throw new Error();
     * }
     * if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {
     * 	throw new Error();
     * }
     * ```
     */
    constructor(parent, ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {
        __publicField(this, "_stackElementBrand");
        /**
         * The position on the current line where this state was pushed.
         * This is relevant only while tokenizing a line, to detect endless loops.
         * Its value is meaningless across lines.
         */
        __publicField(this, "_enterPos");
        /**
         * The captured anchor position when this stack element was pushed.
         * This is relevant only while tokenizing a line, to restore the anchor position when popping.
         * Its value is meaningless across lines.
         */
        __publicField(this, "_anchorPos");
        /**
         * The depth of the stack.
         */
        __publicField(this, "depth");
        this.parent = parent;
        this.ruleId = ruleId;
        this.beginRuleCapturedEOL = beginRuleCapturedEOL;
        this.endRule = endRule;
        this.nameScopesList = nameScopesList;
        this.contentNameScopesList = contentNameScopesList;
        this.depth = this.parent ? this.parent.depth + 1 : 1;
        this._enterPos = enterPos;
        this._anchorPos = anchorPos;
    }

    static _equals(a, b) {
        if (a === b) {
            return true;
        }
        if (!this._structuralEquals(a, b)) {
            return false;
        }
        return AttributedScopeStack.equals(a.contentNameScopesList, b.contentNameScopesList);
    }

    /**
     * A structural equals check. Does not take into account `scopes`.
     */
    static _structuralEquals(a, b) {
        do {
            if (a === b) {
                return true;
            }
            if (!a && !b) {
                return true;
            }
            if (!a || !b) {
                return false;
            }
            if (a.depth !== b.depth || a.ruleId !== b.ruleId || a.endRule !== b.endRule) {
                return false;
            }
            a = a.parent;
            b = b.parent;
        } while (true);
    }

    static _reset(el) {
        while (el) {
            el._enterPos = -1;
            el._anchorPos = -1;
            el = el.parent;
        }
    }

    static pushFrame(self, frame) {
        var _a2, _b2, _c;
        const namesScopeList = AttributedScopeStack.fromExtension((_a2 = self == null ? void 0 : self.nameScopesList) != null ? _a2 : null, frame.nameScopesList);
        return new _b(
            self,
            ruleIdFromNumber(frame.ruleId),
            (_b2 = frame.enterPos) != null ? _b2 : -1,
            (_c = frame.anchorPos) != null ? _c : -1,
            frame.beginRuleCapturedEOL,
            frame.endRule,
            namesScopeList,
            AttributedScopeStack.fromExtension(namesScopeList, frame.contentNameScopesList)
        );
    }

    equals(other) {
        if (other === null) {
            return false;
        }
        return _b._equals(this, other);
    }

    clone() {
        return this;
    }

    reset() {
        _b._reset(this);
    }

    pop() {
        return this.parent;
    }

    safePop() {
        if (this.parent) {
            return this.parent;
        }
        return this;
    }

    push(ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {
        return new _b(
            this,
            ruleId,
            enterPos,
            anchorPos,
            beginRuleCapturedEOL,
            endRule,
            nameScopesList,
            contentNameScopesList
        );
    }

    getEnterPos() {
        return this._enterPos;
    }

    getAnchorPos() {
        return this._anchorPos;
    }

    getRule(grammar) {
        return grammar.getRule(this.ruleId);
    }

    toString() {
        const r = [];
        this._writeString(r, 0);
        return "[" + r.join(",") + "]";
    }

    _writeString(res, outIndex) {
        var _a2, _b2;
        if (this.parent) {
            outIndex = this.parent._writeString(res, outIndex);
        }
        res[outIndex++] = "(".concat(this.ruleId, ", ").concat((_a2 = this.nameScopesList) == null ? void 0 : _a2.toString(), ", ").concat((_b2 = this.contentNameScopesList) == null ? void 0 : _b2.toString(), ")");
        return outIndex;
    }

    withContentNameScopesList(contentNameScopeStack) {
        if (this.contentNameScopesList === contentNameScopeStack) {
            return this;
        }
        return this.parent.push(
            this.ruleId,
            this._enterPos,
            this._anchorPos,
            this.beginRuleCapturedEOL,
            this.endRule,
            this.nameScopesList,
            contentNameScopeStack
        );
    }

    withEndRule(endRule) {
        if (this.endRule === endRule) {
            return this;
        }
        return new _b(
            this.parent,
            this.ruleId,
            this._enterPos,
            this._anchorPos,
            this.beginRuleCapturedEOL,
            endRule,
            this.nameScopesList,
            this.contentNameScopesList
        );
    }

    // Used to warn of endless loops
    hasSameRuleAs(other) {
        let el = this;
        while (el && el._enterPos === other._enterPos) {
            if (el.ruleId === other.ruleId) {
                return true;
            }
            el = el.parent;
        }
        return false;
    }

    toStateStackFrame() {
        var _a2, _b2, _c, _d, _e, _f;
        return {
            ruleId: ruleIdToNumber(this.ruleId),
            beginRuleCapturedEOL: this.beginRuleCapturedEOL,
            endRule: this.endRule,
            nameScopesList: (_d = (_c = this.nameScopesList) == null ? void 0 : _c.getExtensionIfDefined((_b2 = (_a2 = this.parent) == null ? void 0 : _a2.nameScopesList) != null ? _b2 : null)) != null ? _d : [],
            contentNameScopesList: (_f = (_e = this.contentNameScopesList) == null ? void 0 : _e.getExtensionIfDefined(this.nameScopesList)) != null ? _f : []
        };
    }
}, // TODO remove me
    __publicField(_b, "NULL", new _b(
        null,
        0,
        0,
        0,
        false,
        null,
        null,
        null
    )), _b);
var BalancedBracketSelectors = class {
    constructor(balancedBracketScopes, unbalancedBracketScopes) {
        __publicField(this, "balancedBracketScopes");
        __publicField(this, "unbalancedBracketScopes");
        __publicField(this, "allowAny", false);
        this.balancedBracketScopes = balancedBracketScopes.flatMap(
            (selector) => {
                if (selector === "*") {
                    this.allowAny = true;
                    return [];
                }
                return createMatchers(selector, nameMatcher).map((m) => m.matcher);
            }
        );
        this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap(
            (selector) => createMatchers(selector, nameMatcher).map((m) => m.matcher)
        );
    }

    get matchesAlways() {
        return this.allowAny && this.unbalancedBracketScopes.length === 0;
    }

    get matchesNever() {
        return this.balancedBracketScopes.length === 0 && !this.allowAny;
    }

    match(scopes) {
        for (const excluder of this.unbalancedBracketScopes) {
            if (excluder(scopes)) {
                return false;
            }
        }
        for (const includer of this.balancedBracketScopes) {
            if (includer(scopes)) {
                return true;
            }
        }
        return this.allowAny;
    }
};
var LineTokens = class {
    constructor(emitBinaryTokens, lineText, tokenTypeOverrides, balancedBracketSelectors) {
        __publicField(this, "_emitBinaryTokens");
        /**
         * defined only if `false`.
         */
        __publicField(this, "_lineText");
        /**
         * used only if `_emitBinaryTokens` is false.
         */
        __publicField(this, "_tokens");
        /**
         * used only if `_emitBinaryTokens` is true.
         */
        __publicField(this, "_binaryTokens");
        __publicField(this, "_lastTokenEndIndex");
        __publicField(this, "_tokenTypeOverrides");
        this.balancedBracketSelectors = balancedBracketSelectors;
        this._emitBinaryTokens = emitBinaryTokens;
        this._tokenTypeOverrides = tokenTypeOverrides;
        {
            this._lineText = null;
        }
        this._tokens = [];
        this._binaryTokens = [];
        this._lastTokenEndIndex = 0;
    }

    produce(stack, endIndex) {
        this.produceFromScopes(stack.contentNameScopesList, endIndex);
    }

    produceFromScopes(scopesList, endIndex) {
        var _a2, _b2, _c, _d;
        if (this._lastTokenEndIndex >= endIndex) {
            return;
        }
        if (this._emitBinaryTokens) {
            let metadata = (_a2 = scopesList == null ? void 0 : scopesList.tokenAttributes) != null ? _a2 : 0;
            let containsBalancedBrackets = false;
            if ((_b2 = this.balancedBracketSelectors) == null ? void 0 : _b2.matchesAlways) {
                containsBalancedBrackets = true;
            }
            if (this._tokenTypeOverrides.length > 0 || this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever) {
                const scopes2 = (_c = scopesList == null ? void 0 : scopesList.getScopeNames()) != null ? _c : [];
                for (const tokenType of this._tokenTypeOverrides) {
                    if (tokenType.matcher(scopes2)) {
                        metadata = EncodedTokenMetadata.set(
                            metadata,
                            0,
                            toOptionalTokenType(tokenType.type),
                            null,
                            -1,
                            0,
                            0
                        );
                    }
                }
                if (this.balancedBracketSelectors) {
                    containsBalancedBrackets = this.balancedBracketSelectors.match(scopes2);
                }
            }
            if (containsBalancedBrackets) {
                metadata = EncodedTokenMetadata.set(
                    metadata,
                    0,
                    8,
                    containsBalancedBrackets,
                    -1,
                    0,
                    0
                );
            }
            if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === metadata) {
                this._lastTokenEndIndex = endIndex;
                return;
            }
            this._binaryTokens.push(this._lastTokenEndIndex);
            this._binaryTokens.push(metadata);
            this._lastTokenEndIndex = endIndex;
            return;
        }
        const scopes = (_d = scopesList == null ? void 0 : scopesList.getScopeNames()) != null ? _d : [];
        this._tokens.push({
            startIndex: this._lastTokenEndIndex,
            endIndex,
            // value: lineText.substring(lastTokenEndIndex, endIndex),
            scopes
        });
        this._lastTokenEndIndex = endIndex;
    }

    getResult(stack, lineLength) {
        if (this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === lineLength - 1) {
            this._tokens.pop();
        }
        if (this._tokens.length === 0) {
            this._lastTokenEndIndex = -1;
            this.produce(stack, lineLength);
            this._tokens[this._tokens.length - 1].startIndex = 0;
        }
        return this._tokens;
    }

    getBinaryResult(stack, lineLength) {
        if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === lineLength - 1) {
            this._binaryTokens.pop();
            this._binaryTokens.pop();
        }
        if (this._binaryTokens.length === 0) {
            this._lastTokenEndIndex = -1;
            this.produce(stack, lineLength);
            this._binaryTokens[this._binaryTokens.length - 2] = 0;
        }
        const result = new Uint32Array(this._binaryTokens.length);
        for (let i = 0, len = this._binaryTokens.length; i < len; i++) {
            result[i] = this._binaryTokens[i];
        }
        return result;
    }
};
var SyncRegistry = class {
    constructor(theme, _onigLib) {
        __publicField(this, "_grammars", /* @__PURE__ */ new Map());
        __publicField(this, "_rawGrammars", /* @__PURE__ */ new Map());
        __publicField(this, "_injectionGrammars", /* @__PURE__ */ new Map());
        __publicField(this, "_theme");
        this._onigLib = _onigLib;
        this._theme = theme;
    }

    dispose() {
        for (const grammar of this._grammars.values()) {
            grammar.dispose();
        }
    }

    setTheme(theme) {
        this._theme = theme;
    }

    getColorMap() {
        return this._theme.getColorMap();
    }

    /**
     * Add `grammar` to registry and return a list of referenced scope names
     */
    addGrammar(grammar, injectionScopeNames) {
        this._rawGrammars.set(grammar.scopeName, grammar);
        if (injectionScopeNames) {
            this._injectionGrammars.set(grammar.scopeName, injectionScopeNames);
        }
    }

    /**
     * Lookup a raw grammar.
     */
    lookup(scopeName) {
        return this._rawGrammars.get(scopeName);
    }

    /**
     * Returns the injections for the given grammar
     */
    injections(targetScope) {
        return this._injectionGrammars.get(targetScope);
    }

    /**
     * Get the default theme settings
     */
    getDefaults() {
        return this._theme.getDefaults();
    }

    /**
     * Match a scope in the theme.
     */
    themeMatch(scopePath) {
        return this._theme.match(scopePath);
    }

    /**
     * Lookup a grammar.
     */
    grammarForScopeName(scopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {
        if (!this._grammars.has(scopeName)) {
            let rawGrammar = this._rawGrammars.get(scopeName);
            if (!rawGrammar) {
                return null;
            }
            this._grammars.set(scopeName, createGrammar(
                scopeName,
                rawGrammar,
                initialLanguage,
                embeddedLanguages,
                tokenTypes,
                balancedBracketSelectors,
                this,
                this._onigLib
            ));
        }
        return this._grammars.get(scopeName);
    }
};
var Registry$1 = class Registry {
    constructor(options) {
        __publicField(this, "_options");
        __publicField(this, "_syncRegistry");
        __publicField(this, "_ensureGrammarCache");
        this._options = options;
        this._syncRegistry = new SyncRegistry(
            Theme.createFromRawTheme(options.theme, options.colorMap),
            options.onigLib
        );
        this._ensureGrammarCache = /* @__PURE__ */ new Map();
    }

    dispose() {
        this._syncRegistry.dispose();
    }

    /**
     * Change the theme. Once called, no previous `ruleStack` should be used anymore.
     */
    setTheme(theme, colorMap) {
        this._syncRegistry.setTheme(Theme.createFromRawTheme(theme, colorMap));
    }

    /**
     * Returns a lookup array for color ids.
     */
    getColorMap() {
        return this._syncRegistry.getColorMap();
    }

    /**
     * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
     * Please do not use language id 0.
     */
    loadGrammarWithEmbeddedLanguages(initialScopeName, initialLanguage, embeddedLanguages) {
        return this.loadGrammarWithConfiguration(initialScopeName, initialLanguage, {embeddedLanguages});
    }

    /**
     * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
     * Please do not use language id 0.
     */
    loadGrammarWithConfiguration(initialScopeName, initialLanguage, configuration) {
        return this._loadGrammar(
            initialScopeName,
            initialLanguage,
            configuration.embeddedLanguages,
            configuration.tokenTypes,
            new BalancedBracketSelectors(
                configuration.balancedBracketSelectors || [],
                configuration.unbalancedBracketSelectors || []
            )
        );
    }

    /**
     * Load the grammar for `scopeName` and all referenced included grammars asynchronously.
     */
    loadGrammar(initialScopeName) {
        return this._loadGrammar(initialScopeName, 0, null, null, null);
    }

    _loadGrammar(initialScopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {
        const dependencyProcessor = new ScopeDependencyProcessor(this._syncRegistry, initialScopeName);
        while (dependencyProcessor.Q.length > 0) {
            dependencyProcessor.Q.map((request) => this._loadSingleGrammar(request.scopeName));
            dependencyProcessor.processQueue();
        }
        return this._grammarForScopeName(
            initialScopeName,
            initialLanguage,
            embeddedLanguages,
            tokenTypes,
            balancedBracketSelectors
        );
    }

    _loadSingleGrammar(scopeName) {
        if (!this._ensureGrammarCache.has(scopeName)) {
            this._doLoadSingleGrammar(scopeName);
            this._ensureGrammarCache.set(scopeName, true);
        }
    }

    _doLoadSingleGrammar(scopeName) {
        const grammar = this._options.loadGrammar(scopeName);
        if (grammar) {
            const injections = typeof this._options.getInjections === "function" ? this._options.getInjections(scopeName) : void 0;
            this._syncRegistry.addGrammar(grammar, injections);
        }
    }

    /**
     * Adds a rawGrammar.
     */
    addGrammar(rawGrammar, injections = [], initialLanguage = 0, embeddedLanguages = null) {
        this._syncRegistry.addGrammar(rawGrammar, injections);
        return this._grammarForScopeName(rawGrammar.scopeName, initialLanguage, embeddedLanguages);
    }

    /**
     * Get the grammar for `scopeName`. The grammar must first be created via `loadGrammar` or `addGrammar`.
     */
    _grammarForScopeName(scopeName, initialLanguage = 0, embeddedLanguages = null, tokenTypes = null, balancedBracketSelectors = null) {
        return this._syncRegistry.grammarForScopeName(
            scopeName,
            initialLanguage,
            embeddedLanguages,
            tokenTypes,
            balancedBracketSelectors
        );
    }
};
var INITIAL = StateStackImpl.NULL;
const htmlVoidElements = [
    "area",
    "base",
    "basefont",
    "bgsound",
    "br",
    "col",
    "command",
    "embed",
    "frame",
    "hr",
    "image",
    "img",
    "input",
    "keygen",
    "link",
    "meta",
    "param",
    "source",
    "track",
    "wbr"
];

class Schema {
    /**
     * @constructor
     * @param {Properties} property
     * @param {Normal} normal
     * @param {string} [space]
     */
    constructor(property, normal, space) {
        this.property = property;
        this.normal = normal;
        if (space) {
            this.space = space;
        }
    }
}

Schema.prototype.property = {};
Schema.prototype.normal = {};
Schema.prototype.space = null;

function merge(definitions, space) {
    const property = {};
    const normal = {};
    let index = -1;
    while (++index < definitions.length) {
        Object.assign(property, definitions[index].property);
        Object.assign(normal, definitions[index].normal);
    }
    return new Schema(property, normal, space);
}

function normalize(value) {
    return value.toLowerCase();
}

class Info {
    /**
     * @constructor
     * @param {string} property
     * @param {string} attribute
     */
    constructor(property, attribute) {
        this.property = property;
        this.attribute = attribute;
    }
}

Info.prototype.space = null;
Info.prototype.boolean = false;
Info.prototype.booleanish = false;
Info.prototype.overloadedBoolean = false;
Info.prototype.number = false;
Info.prototype.commaSeparated = false;
Info.prototype.spaceSeparated = false;
Info.prototype.commaOrSpaceSeparated = false;
Info.prototype.mustUseProperty = false;
Info.prototype.defined = false;
let powers = 0;
const boolean = increment();
const booleanish = increment();
const overloadedBoolean = increment();
const number = increment();
const spaceSeparated = increment();
const commaSeparated = increment();
const commaOrSpaceSeparated = increment();

function increment() {
    return 2 ** ++powers;
}

const types = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    boolean,
    booleanish,
    commaOrSpaceSeparated,
    commaSeparated,
    number,
    overloadedBoolean,
    spaceSeparated
}, Symbol.toStringTag, {value: "Module"}));
const checks = Object.keys(types);

class DefinedInfo extends Info {
    /**
     * @constructor
     * @param {string} property
     * @param {string} attribute
     * @param {number|null} [mask]
     * @param {string} [space]
     */
    constructor(property, attribute, mask, space) {
        let index = -1;
        super(property, attribute);
        mark(this, "space", space);
        if (typeof mask === "number") {
            while (++index < checks.length) {
                const check = checks[index];
                mark(this, checks[index], (mask & types[check]) === types[check]);
            }
        }
    }
}

DefinedInfo.prototype.defined = true;

function mark(values, key2, value) {
    if (value) {
        values[key2] = value;
    }
}

const own$3 = {}.hasOwnProperty;

function create(definition) {
    const property = {};
    const normal = {};
    let prop;
    for (prop in definition.properties) {
        if (own$3.call(definition.properties, prop)) {
            const value = definition.properties[prop];
            const info = new DefinedInfo(
                prop,
                definition.transform(definition.attributes || {}, prop),
                value,
                definition.space
            );
            if (definition.mustUseProperty && definition.mustUseProperty.includes(prop)) {
                info.mustUseProperty = true;
            }
            property[prop] = info;
            normal[normalize(prop)] = prop;
            normal[normalize(info.attribute)] = prop;
        }
    }
    return new Schema(property, normal, definition.space);
}

const xlink = create({
    space: "xlink",
    transform(_, prop) {
        return "xlink:" + prop.slice(5).toLowerCase();
    },
    properties: {
        xLinkActuate: null,
        xLinkArcRole: null,
        xLinkHref: null,
        xLinkRole: null,
        xLinkShow: null,
        xLinkTitle: null,
        xLinkType: null
    }
});
const xml = create({
    space: "xml",
    transform(_, prop) {
        return "xml:" + prop.slice(3).toLowerCase();
    },
    properties: {xmlLang: null, xmlBase: null, xmlSpace: null}
});

function caseSensitiveTransform(attributes, attribute) {
    return attribute in attributes ? attributes[attribute] : attribute;
}

function caseInsensitiveTransform(attributes, property) {
    return caseSensitiveTransform(attributes, property.toLowerCase());
}

const xmlns = create({
    space: "xmlns",
    attributes: {xmlnsxlink: "xmlns:xlink"},
    transform: caseInsensitiveTransform,
    properties: {xmlns: null, xmlnsXLink: null}
});
const aria = create({
    transform(_, prop) {
        return prop === "role" ? prop : "aria-" + prop.slice(4).toLowerCase();
    },
    properties: {
        ariaActiveDescendant: null,
        ariaAtomic: booleanish,
        ariaAutoComplete: null,
        ariaBusy: booleanish,
        ariaChecked: booleanish,
        ariaColCount: number,
        ariaColIndex: number,
        ariaColSpan: number,
        ariaControls: spaceSeparated,
        ariaCurrent: null,
        ariaDescribedBy: spaceSeparated,
        ariaDetails: null,
        ariaDisabled: booleanish,
        ariaDropEffect: spaceSeparated,
        ariaErrorMessage: null,
        ariaExpanded: booleanish,
        ariaFlowTo: spaceSeparated,
        ariaGrabbed: booleanish,
        ariaHasPopup: null,
        ariaHidden: booleanish,
        ariaInvalid: null,
        ariaKeyShortcuts: null,
        ariaLabel: null,
        ariaLabelledBy: spaceSeparated,
        ariaLevel: number,
        ariaLive: null,
        ariaModal: booleanish,
        ariaMultiLine: booleanish,
        ariaMultiSelectable: booleanish,
        ariaOrientation: null,
        ariaOwns: spaceSeparated,
        ariaPlaceholder: null,
        ariaPosInSet: number,
        ariaPressed: booleanish,
        ariaReadOnly: booleanish,
        ariaRelevant: null,
        ariaRequired: booleanish,
        ariaRoleDescription: spaceSeparated,
        ariaRowCount: number,
        ariaRowIndex: number,
        ariaRowSpan: number,
        ariaSelected: booleanish,
        ariaSetSize: number,
        ariaSort: null,
        ariaValueMax: number,
        ariaValueMin: number,
        ariaValueNow: number,
        ariaValueText: null,
        role: null
    }
});
const html$3 = create({
    space: "html",
    attributes: {
        acceptcharset: "accept-charset",
        classname: "class",
        htmlfor: "for",
        httpequiv: "http-equiv"
    },
    transform: caseInsensitiveTransform,
    mustUseProperty: ["checked", "multiple", "muted", "selected"],
    properties: {
        // Standard Properties.
        abbr: null,
        accept: commaSeparated,
        acceptCharset: spaceSeparated,
        accessKey: spaceSeparated,
        action: null,
        allow: null,
        allowFullScreen: boolean,
        allowPaymentRequest: boolean,
        allowUserMedia: boolean,
        alt: null,
        as: null,
        async: boolean,
        autoCapitalize: null,
        autoComplete: spaceSeparated,
        autoFocus: boolean,
        autoPlay: boolean,
        blocking: spaceSeparated,
        capture: null,
        charSet: null,
        checked: boolean,
        cite: null,
        className: spaceSeparated,
        cols: number,
        colSpan: null,
        content: null,
        contentEditable: booleanish,
        controls: boolean,
        controlsList: spaceSeparated,
        coords: number | commaSeparated,
        crossOrigin: null,
        data: null,
        dateTime: null,
        decoding: null,
        default: boolean,
        defer: boolean,
        dir: null,
        dirName: null,
        disabled: boolean,
        download: overloadedBoolean,
        draggable: booleanish,
        encType: null,
        enterKeyHint: null,
        fetchPriority: null,
        form: null,
        formAction: null,
        formEncType: null,
        formMethod: null,
        formNoValidate: boolean,
        formTarget: null,
        headers: spaceSeparated,
        height: number,
        hidden: boolean,
        high: number,
        href: null,
        hrefLang: null,
        htmlFor: spaceSeparated,
        httpEquiv: spaceSeparated,
        id: null,
        imageSizes: null,
        imageSrcSet: null,
        inert: boolean,
        inputMode: null,
        integrity: null,
        is: null,
        isMap: boolean,
        itemId: null,
        itemProp: spaceSeparated,
        itemRef: spaceSeparated,
        itemScope: boolean,
        itemType: spaceSeparated,
        kind: null,
        label: null,
        lang: null,
        language: null,
        list: null,
        loading: null,
        loop: boolean,
        low: number,
        manifest: null,
        max: null,
        maxLength: number,
        media: null,
        method: null,
        min: null,
        minLength: number,
        multiple: boolean,
        muted: boolean,
        name: null,
        nonce: null,
        noModule: boolean,
        noValidate: boolean,
        onAbort: null,
        onAfterPrint: null,
        onAuxClick: null,
        onBeforeMatch: null,
        onBeforePrint: null,
        onBeforeToggle: null,
        onBeforeUnload: null,
        onBlur: null,
        onCancel: null,
        onCanPlay: null,
        onCanPlayThrough: null,
        onChange: null,
        onClick: null,
        onClose: null,
        onContextLost: null,
        onContextMenu: null,
        onContextRestored: null,
        onCopy: null,
        onCueChange: null,
        onCut: null,
        onDblClick: null,
        onDrag: null,
        onDragEnd: null,
        onDragEnter: null,
        onDragExit: null,
        onDragLeave: null,
        onDragOver: null,
        onDragStart: null,
        onDrop: null,
        onDurationChange: null,
        onEmptied: null,
        onEnded: null,
        onError: null,
        onFocus: null,
        onFormData: null,
        onHashChange: null,
        onInput: null,
        onInvalid: null,
        onKeyDown: null,
        onKeyPress: null,
        onKeyUp: null,
        onLanguageChange: null,
        onLoad: null,
        onLoadedData: null,
        onLoadedMetadata: null,
        onLoadEnd: null,
        onLoadStart: null,
        onMessage: null,
        onMessageError: null,
        onMouseDown: null,
        onMouseEnter: null,
        onMouseLeave: null,
        onMouseMove: null,
        onMouseOut: null,
        onMouseOver: null,
        onMouseUp: null,
        onOffline: null,
        onOnline: null,
        onPageHide: null,
        onPageShow: null,
        onPaste: null,
        onPause: null,
        onPlay: null,
        onPlaying: null,
        onPopState: null,
        onProgress: null,
        onRateChange: null,
        onRejectionHandled: null,
        onReset: null,
        onResize: null,
        onScroll: null,
        onScrollEnd: null,
        onSecurityPolicyViolation: null,
        onSeeked: null,
        onSeeking: null,
        onSelect: null,
        onSlotChange: null,
        onStalled: null,
        onStorage: null,
        onSubmit: null,
        onSuspend: null,
        onTimeUpdate: null,
        onToggle: null,
        onUnhandledRejection: null,
        onUnload: null,
        onVolumeChange: null,
        onWaiting: null,
        onWheel: null,
        open: boolean,
        optimum: number,
        pattern: null,
        ping: spaceSeparated,
        placeholder: null,
        playsInline: boolean,
        popover: null,
        popoverTarget: null,
        popoverTargetAction: null,
        poster: null,
        preload: null,
        readOnly: boolean,
        referrerPolicy: null,
        rel: spaceSeparated,
        required: boolean,
        reversed: boolean,
        rows: number,
        rowSpan: number,
        sandbox: spaceSeparated,
        scope: null,
        scoped: boolean,
        seamless: boolean,
        selected: boolean,
        shadowRootClonable: boolean,
        shadowRootDelegatesFocus: boolean,
        shadowRootMode: null,
        shape: null,
        size: number,
        sizes: null,
        slot: null,
        span: number,
        spellCheck: booleanish,
        src: null,
        srcDoc: null,
        srcLang: null,
        srcSet: null,
        start: number,
        step: null,
        style: null,
        tabIndex: number,
        target: null,
        title: null,
        translate: null,
        type: null,
        typeMustMatch: boolean,
        useMap: null,
        value: booleanish,
        width: number,
        wrap: null,
        writingSuggestions: null,
        // Legacy.
        // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis
        align: null,
        // Several. Use CSS `text-align` instead,
        aLink: null,
        // `<body>`. Use CSS `a:active {color}` instead
        archive: spaceSeparated,
        // `<object>`. List of URIs to archives
        axis: null,
        // `<td>` and `<th>`. Use `scope` on `<th>`
        background: null,
        // `<body>`. Use CSS `background-image` instead
        bgColor: null,
        // `<body>` and table elements. Use CSS `background-color` instead
        border: number,
        // `<table>`. Use CSS `border-width` instead,
        borderColor: null,
        // `<table>`. Use CSS `border-color` instead,
        bottomMargin: number,
        // `<body>`
        cellPadding: null,
        // `<table>`
        cellSpacing: null,
        // `<table>`
        char: null,
        // Several table elements. When `align=char`, sets the character to align on
        charOff: null,
        // Several table elements. When `char`, offsets the alignment
        classId: null,
        // `<object>`
        clear: null,
        // `<br>`. Use CSS `clear` instead
        code: null,
        // `<object>`
        codeBase: null,
        // `<object>`
        codeType: null,
        // `<object>`
        color: null,
        // `<font>` and `<hr>`. Use CSS instead
        compact: boolean,
        // Lists. Use CSS to reduce space between items instead
        declare: boolean,
        // `<object>`
        event: null,
        // `<script>`
        face: null,
        // `<font>`. Use CSS instead
        frame: null,
        // `<table>`
        frameBorder: null,
        // `<iframe>`. Use CSS `border` instead
        hSpace: number,
        // `<img>` and `<object>`
        leftMargin: number,
        // `<body>`
        link: null,
        // `<body>`. Use CSS `a:link {color: *}` instead
        longDesc: null,
        // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`
        lowSrc: null,
        // `<img>`. Use a `<picture>`
        marginHeight: number,
        // `<body>`
        marginWidth: number,
        // `<body>`
        noResize: boolean,
        // `<frame>`
        noHref: boolean,
        // `<area>`. Use no href instead of an explicit `nohref`
        noShade: boolean,
        // `<hr>`. Use background-color and height instead of borders
        noWrap: boolean,
        // `<td>` and `<th>`
        object: null,
        // `<applet>`
        profile: null,
        // `<head>`
        prompt: null,
        // `<isindex>`
        rev: null,
        // `<link>`
        rightMargin: number,
        // `<body>`
        rules: null,
        // `<table>`
        scheme: null,
        // `<meta>`
        scrolling: booleanish,
        // `<frame>`. Use overflow in the child context
        standby: null,
        // `<object>`
        summary: null,
        // `<table>`
        text: null,
        // `<body>`. Use CSS `color` instead
        topMargin: number,
        // `<body>`
        valueType: null,
        // `<param>`
        version: null,
        // `<html>`. Use a doctype.
        vAlign: null,
        // Several. Use CSS `vertical-align` instead
        vLink: null,
        // `<body>`. Use CSS `a:visited {color}` instead
        vSpace: number,
        // `<img>` and `<object>`
        // Non-standard Properties.
        allowTransparency: null,
        autoCorrect: null,
        autoSave: null,
        disablePictureInPicture: boolean,
        disableRemotePlayback: boolean,
        prefix: null,
        property: null,
        results: number,
        security: null,
        unselectable: null
    }
});
const svg$1 = create({
    space: "svg",
    attributes: {
        accentHeight: "accent-height",
        alignmentBaseline: "alignment-baseline",
        arabicForm: "arabic-form",
        baselineShift: "baseline-shift",
        capHeight: "cap-height",
        className: "class",
        clipPath: "clip-path",
        clipRule: "clip-rule",
        colorInterpolation: "color-interpolation",
        colorInterpolationFilters: "color-interpolation-filters",
        colorProfile: "color-profile",
        colorRendering: "color-rendering",
        crossOrigin: "crossorigin",
        dataType: "datatype",
        dominantBaseline: "dominant-baseline",
        enableBackground: "enable-background",
        fillOpacity: "fill-opacity",
        fillRule: "fill-rule",
        floodColor: "flood-color",
        floodOpacity: "flood-opacity",
        fontFamily: "font-family",
        fontSize: "font-size",
        fontSizeAdjust: "font-size-adjust",
        fontStretch: "font-stretch",
        fontStyle: "font-style",
        fontVariant: "font-variant",
        fontWeight: "font-weight",
        glyphName: "glyph-name",
        glyphOrientationHorizontal: "glyph-orientation-horizontal",
        glyphOrientationVertical: "glyph-orientation-vertical",
        hrefLang: "hreflang",
        horizAdvX: "horiz-adv-x",
        horizOriginX: "horiz-origin-x",
        horizOriginY: "horiz-origin-y",
        imageRendering: "image-rendering",
        letterSpacing: "letter-spacing",
        lightingColor: "lighting-color",
        markerEnd: "marker-end",
        markerMid: "marker-mid",
        markerStart: "marker-start",
        navDown: "nav-down",
        navDownLeft: "nav-down-left",
        navDownRight: "nav-down-right",
        navLeft: "nav-left",
        navNext: "nav-next",
        navPrev: "nav-prev",
        navRight: "nav-right",
        navUp: "nav-up",
        navUpLeft: "nav-up-left",
        navUpRight: "nav-up-right",
        onAbort: "onabort",
        onActivate: "onactivate",
        onAfterPrint: "onafterprint",
        onBeforePrint: "onbeforeprint",
        onBegin: "onbegin",
        onCancel: "oncancel",
        onCanPlay: "oncanplay",
        onCanPlayThrough: "oncanplaythrough",
        onChange: "onchange",
        onClick: "onclick",
        onClose: "onclose",
        onCopy: "oncopy",
        onCueChange: "oncuechange",
        onCut: "oncut",
        onDblClick: "ondblclick",
        onDrag: "ondrag",
        onDragEnd: "ondragend",
        onDragEnter: "ondragenter",
        onDragExit: "ondragexit",
        onDragLeave: "ondragleave",
        onDragOver: "ondragover",
        onDragStart: "ondragstart",
        onDrop: "ondrop",
        onDurationChange: "ondurationchange",
        onEmptied: "onemptied",
        onEnd: "onend",
        onEnded: "onended",
        onError: "onerror",
        onFocus: "onfocus",
        onFocusIn: "onfocusin",
        onFocusOut: "onfocusout",
        onHashChange: "onhashchange",
        onInput: "oninput",
        onInvalid: "oninvalid",
        onKeyDown: "onkeydown",
        onKeyPress: "onkeypress",
        onKeyUp: "onkeyup",
        onLoad: "onload",
        onLoadedData: "onloadeddata",
        onLoadedMetadata: "onloadedmetadata",
        onLoadStart: "onloadstart",
        onMessage: "onmessage",
        onMouseDown: "onmousedown",
        onMouseEnter: "onmouseenter",
        onMouseLeave: "onmouseleave",
        onMouseMove: "onmousemove",
        onMouseOut: "onmouseout",
        onMouseOver: "onmouseover",
        onMouseUp: "onmouseup",
        onMouseWheel: "onmousewheel",
        onOffline: "onoffline",
        onOnline: "ononline",
        onPageHide: "onpagehide",
        onPageShow: "onpageshow",
        onPaste: "onpaste",
        onPause: "onpause",
        onPlay: "onplay",
        onPlaying: "onplaying",
        onPopState: "onpopstate",
        onProgress: "onprogress",
        onRateChange: "onratechange",
        onRepeat: "onrepeat",
        onReset: "onreset",
        onResize: "onresize",
        onScroll: "onscroll",
        onSeeked: "onseeked",
        onSeeking: "onseeking",
        onSelect: "onselect",
        onShow: "onshow",
        onStalled: "onstalled",
        onStorage: "onstorage",
        onSubmit: "onsubmit",
        onSuspend: "onsuspend",
        onTimeUpdate: "ontimeupdate",
        onToggle: "ontoggle",
        onUnload: "onunload",
        onVolumeChange: "onvolumechange",
        onWaiting: "onwaiting",
        onZoom: "onzoom",
        overlinePosition: "overline-position",
        overlineThickness: "overline-thickness",
        paintOrder: "paint-order",
        panose1: "panose-1",
        pointerEvents: "pointer-events",
        referrerPolicy: "referrerpolicy",
        renderingIntent: "rendering-intent",
        shapeRendering: "shape-rendering",
        stopColor: "stop-color",
        stopOpacity: "stop-opacity",
        strikethroughPosition: "strikethrough-position",
        strikethroughThickness: "strikethrough-thickness",
        strokeDashArray: "stroke-dasharray",
        strokeDashOffset: "stroke-dashoffset",
        strokeLineCap: "stroke-linecap",
        strokeLineJoin: "stroke-linejoin",
        strokeMiterLimit: "stroke-miterlimit",
        strokeOpacity: "stroke-opacity",
        strokeWidth: "stroke-width",
        tabIndex: "tabindex",
        textAnchor: "text-anchor",
        textDecoration: "text-decoration",
        textRendering: "text-rendering",
        transformOrigin: "transform-origin",
        typeOf: "typeof",
        underlinePosition: "underline-position",
        underlineThickness: "underline-thickness",
        unicodeBidi: "unicode-bidi",
        unicodeRange: "unicode-range",
        unitsPerEm: "units-per-em",
        vAlphabetic: "v-alphabetic",
        vHanging: "v-hanging",
        vIdeographic: "v-ideographic",
        vMathematical: "v-mathematical",
        vectorEffect: "vector-effect",
        vertAdvY: "vert-adv-y",
        vertOriginX: "vert-origin-x",
        vertOriginY: "vert-origin-y",
        wordSpacing: "word-spacing",
        writingMode: "writing-mode",
        xHeight: "x-height",
        // These were camelcased in Tiny. Now lowercased in SVG 2
        playbackOrder: "playbackorder",
        timelineBegin: "timelinebegin"
    },
    transform: caseSensitiveTransform,
    properties: {
        about: commaOrSpaceSeparated,
        accentHeight: number,
        accumulate: null,
        additive: null,
        alignmentBaseline: null,
        alphabetic: number,
        amplitude: number,
        arabicForm: null,
        ascent: number,
        attributeName: null,
        attributeType: null,
        azimuth: number,
        bandwidth: null,
        baselineShift: null,
        baseFrequency: null,
        baseProfile: null,
        bbox: null,
        begin: null,
        bias: number,
        by: null,
        calcMode: null,
        capHeight: number,
        className: spaceSeparated,
        clip: null,
        clipPath: null,
        clipPathUnits: null,
        clipRule: null,
        color: null,
        colorInterpolation: null,
        colorInterpolationFilters: null,
        colorProfile: null,
        colorRendering: null,
        content: null,
        contentScriptType: null,
        contentStyleType: null,
        crossOrigin: null,
        cursor: null,
        cx: null,
        cy: null,
        d: null,
        dataType: null,
        defaultAction: null,
        descent: number,
        diffuseConstant: number,
        direction: null,
        display: null,
        dur: null,
        divisor: number,
        dominantBaseline: null,
        download: boolean,
        dx: null,
        dy: null,
        edgeMode: null,
        editable: null,
        elevation: number,
        enableBackground: null,
        end: null,
        event: null,
        exponent: number,
        externalResourcesRequired: null,
        fill: null,
        fillOpacity: number,
        fillRule: null,
        filter: null,
        filterRes: null,
        filterUnits: null,
        floodColor: null,
        floodOpacity: null,
        focusable: null,
        focusHighlight: null,
        fontFamily: null,
        fontSize: null,
        fontSizeAdjust: null,
        fontStretch: null,
        fontStyle: null,
        fontVariant: null,
        fontWeight: null,
        format: null,
        fr: null,
        from: null,
        fx: null,
        fy: null,
        g1: commaSeparated,
        g2: commaSeparated,
        glyphName: commaSeparated,
        glyphOrientationHorizontal: null,
        glyphOrientationVertical: null,
        glyphRef: null,
        gradientTransform: null,
        gradientUnits: null,
        handler: null,
        hanging: number,
        hatchContentUnits: null,
        hatchUnits: null,
        height: null,
        href: null,
        hrefLang: null,
        horizAdvX: number,
        horizOriginX: number,
        horizOriginY: number,
        id: null,
        ideographic: number,
        imageRendering: null,
        initialVisibility: null,
        in: null,
        in2: null,
        intercept: number,
        k: number,
        k1: number,
        k2: number,
        k3: number,
        k4: number,
        kernelMatrix: commaOrSpaceSeparated,
        kernelUnitLength: null,
        keyPoints: null,
        // SEMI_COLON_SEPARATED
        keySplines: null,
        // SEMI_COLON_SEPARATED
        keyTimes: null,
        // SEMI_COLON_SEPARATED
        kerning: null,
        lang: null,
        lengthAdjust: null,
        letterSpacing: null,
        lightingColor: null,
        limitingConeAngle: number,
        local: null,
        markerEnd: null,
        markerMid: null,
        markerStart: null,
        markerHeight: null,
        markerUnits: null,
        markerWidth: null,
        mask: null,
        maskContentUnits: null,
        maskUnits: null,
        mathematical: null,
        max: null,
        media: null,
        mediaCharacterEncoding: null,
        mediaContentEncodings: null,
        mediaSize: number,
        mediaTime: null,
        method: null,
        min: null,
        mode: null,
        name: null,
        navDown: null,
        navDownLeft: null,
        navDownRight: null,
        navLeft: null,
        navNext: null,
        navPrev: null,
        navRight: null,
        navUp: null,
        navUpLeft: null,
        navUpRight: null,
        numOctaves: null,
        observer: null,
        offset: null,
        onAbort: null,
        onActivate: null,
        onAfterPrint: null,
        onBeforePrint: null,
        onBegin: null,
        onCancel: null,
        onCanPlay: null,
        onCanPlayThrough: null,
        onChange: null,
        onClick: null,
        onClose: null,
        onCopy: null,
        onCueChange: null,
        onCut: null,
        onDblClick: null,
        onDrag: null,
        onDragEnd: null,
        onDragEnter: null,
        onDragExit: null,
        onDragLeave: null,
        onDragOver: null,
        onDragStart: null,
        onDrop: null,
        onDurationChange: null,
        onEmptied: null,
        onEnd: null,
        onEnded: null,
        onError: null,
        onFocus: null,
        onFocusIn: null,
        onFocusOut: null,
        onHashChange: null,
        onInput: null,
        onInvalid: null,
        onKeyDown: null,
        onKeyPress: null,
        onKeyUp: null,
        onLoad: null,
        onLoadedData: null,
        onLoadedMetadata: null,
        onLoadStart: null,
        onMessage: null,
        onMouseDown: null,
        onMouseEnter: null,
        onMouseLeave: null,
        onMouseMove: null,
        onMouseOut: null,
        onMouseOver: null,
        onMouseUp: null,
        onMouseWheel: null,
        onOffline: null,
        onOnline: null,
        onPageHide: null,
        onPageShow: null,
        onPaste: null,
        onPause: null,
        onPlay: null,
        onPlaying: null,
        onPopState: null,
        onProgress: null,
        onRateChange: null,
        onRepeat: null,
        onReset: null,
        onResize: null,
        onScroll: null,
        onSeeked: null,
        onSeeking: null,
        onSelect: null,
        onShow: null,
        onStalled: null,
        onStorage: null,
        onSubmit: null,
        onSuspend: null,
        onTimeUpdate: null,
        onToggle: null,
        onUnload: null,
        onVolumeChange: null,
        onWaiting: null,
        onZoom: null,
        opacity: null,
        operator: null,
        order: null,
        orient: null,
        orientation: null,
        origin: null,
        overflow: null,
        overlay: null,
        overlinePosition: number,
        overlineThickness: number,
        paintOrder: null,
        panose1: null,
        path: null,
        pathLength: number,
        patternContentUnits: null,
        patternTransform: null,
        patternUnits: null,
        phase: null,
        ping: spaceSeparated,
        pitch: null,
        playbackOrder: null,
        pointerEvents: null,
        points: null,
        pointsAtX: number,
        pointsAtY: number,
        pointsAtZ: number,
        preserveAlpha: null,
        preserveAspectRatio: null,
        primitiveUnits: null,
        propagate: null,
        property: commaOrSpaceSeparated,
        r: null,
        radius: null,
        referrerPolicy: null,
        refX: null,
        refY: null,
        rel: commaOrSpaceSeparated,
        rev: commaOrSpaceSeparated,
        renderingIntent: null,
        repeatCount: null,
        repeatDur: null,
        requiredExtensions: commaOrSpaceSeparated,
        requiredFeatures: commaOrSpaceSeparated,
        requiredFonts: commaOrSpaceSeparated,
        requiredFormats: commaOrSpaceSeparated,
        resource: null,
        restart: null,
        result: null,
        rotate: null,
        rx: null,
        ry: null,
        scale: null,
        seed: null,
        shapeRendering: null,
        side: null,
        slope: null,
        snapshotTime: null,
        specularConstant: number,
        specularExponent: number,
        spreadMethod: null,
        spacing: null,
        startOffset: null,
        stdDeviation: null,
        stemh: null,
        stemv: null,
        stitchTiles: null,
        stopColor: null,
        stopOpacity: null,
        strikethroughPosition: number,
        strikethroughThickness: number,
        string: null,
        stroke: null,
        strokeDashArray: commaOrSpaceSeparated,
        strokeDashOffset: null,
        strokeLineCap: null,
        strokeLineJoin: null,
        strokeMiterLimit: number,
        strokeOpacity: number,
        strokeWidth: null,
        style: null,
        surfaceScale: number,
        syncBehavior: null,
        syncBehaviorDefault: null,
        syncMaster: null,
        syncTolerance: null,
        syncToleranceDefault: null,
        systemLanguage: commaOrSpaceSeparated,
        tabIndex: number,
        tableValues: null,
        target: null,
        targetX: number,
        targetY: number,
        textAnchor: null,
        textDecoration: null,
        textRendering: null,
        textLength: null,
        timelineBegin: null,
        title: null,
        transformBehavior: null,
        type: null,
        typeOf: commaOrSpaceSeparated,
        to: null,
        transform: null,
        transformOrigin: null,
        u1: null,
        u2: null,
        underlinePosition: number,
        underlineThickness: number,
        unicode: null,
        unicodeBidi: null,
        unicodeRange: null,
        unitsPerEm: number,
        values: null,
        vAlphabetic: number,
        vMathematical: number,
        vectorEffect: null,
        vHanging: number,
        vIdeographic: number,
        version: null,
        vertAdvY: number,
        vertOriginX: number,
        vertOriginY: number,
        viewBox: null,
        viewTarget: null,
        visibility: null,
        width: null,
        widths: null,
        wordSpacing: null,
        writingMode: null,
        x: null,
        x1: null,
        x2: null,
        xChannelSelector: null,
        xHeight: number,
        y: null,
        y1: null,
        y2: null,
        yChannelSelector: null,
        z: null,
        zoomAndPan: null
    }
});
const valid = /^data[-\w.:]+$/i;
const dash = /-[a-z]/g;
const cap = /[A-Z]/g;

function find(schema, value) {
    const normal = normalize(value);
    let prop = value;
    let Type = Info;
    if (normal in schema.normal) {
        return schema.property[schema.normal[normal]];
    }
    if (normal.length > 4 && normal.slice(0, 4) === "data" && valid.test(value)) {
        if (value.charAt(4) === "-") {
            const rest = value.slice(5).replace(dash, camelcase);
            prop = "data" + rest.charAt(0).toUpperCase() + rest.slice(1);
        } else {
            const rest = value.slice(4);
            if (!dash.test(rest)) {
                let dashes = rest.replace(cap, kebab);
                if (dashes.charAt(0) !== "-") {
                    dashes = "-" + dashes;
                }
                value = "data" + dashes;
            }
        }
        Type = DefinedInfo;
    }
    return new Type(prop, value);
}

function kebab($0) {
    return "-" + $0.toLowerCase();
}

function camelcase($0) {
    return $0.charAt(1).toUpperCase();
}

const html$2 = merge([xml, xlink, xmlns, aria, html$3], "html");
const svg = merge([xml, xlink, xmlns, aria, svg$1], "svg");
const own$2 = {}.hasOwnProperty;

function zwitch(key2, options) {
    const settings = options || {};

    function one2(value, ...parameters) {
        let fn = one2.invalid;
        const handlers = one2.handlers;
        if (value && own$2.call(value, key2)) {
            const id = String(value[key2]);
            fn = own$2.call(handlers, id) ? handlers[id] : one2.unknown;
        }
        if (fn) {
            return fn.call(this, value, ...parameters);
        }
    }

    one2.handlers = settings.handlers || {};
    one2.invalid = settings.invalid;
    one2.unknown = settings.unknown;
    return one2;
}

const defaultSubsetRegex = /["&'<>`]/g;
const surrogatePairsRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
const controlCharactersRegex = (
    // eslint-disable-next-line no-control-regex, unicorn/no-hex-escape
    /[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g
);
const regexEscapeRegex = /[|\\{}()[\]^$+*?.]/g;
const subsetToRegexCache = /* @__PURE__ */ new WeakMap();

function core(value, options) {
    value = value.replace(
        options.subset ? charactersToExpressionCached(options.subset) : defaultSubsetRegex,
        basic
    );
    if (options.subset || options.escapeOnly) {
        return value;
    }
    return value.replace(surrogatePairsRegex, surrogate).replace(controlCharactersRegex, basic);

    function surrogate(pair, index, all2) {
        return options.format(
            (pair.charCodeAt(0) - 55296) * 1024 + pair.charCodeAt(1) - 56320 + 65536,
            all2.charCodeAt(index + 2),
            options
        );
    }

    function basic(character, index, all2) {
        return options.format(
            character.charCodeAt(0),
            all2.charCodeAt(index + 1),
            options
        );
    }
}

function charactersToExpressionCached(subset) {
    let cached = subsetToRegexCache.get(subset);
    if (!cached) {
        cached = charactersToExpression(subset);
        subsetToRegexCache.set(subset, cached);
    }
    return cached;
}

function charactersToExpression(subset) {
    const groups = [];
    let index = -1;
    while (++index < subset.length) {
        groups.push(subset[index].replace(regexEscapeRegex, "\\$&"));
    }
    return new RegExp("(?:" + groups.join("|") + ")", "g");
}

const hexadecimalRegex = /[\dA-Fa-f]/;

function toHexadecimal(code, next, omit) {
    const value = "&#x" + code.toString(16).toUpperCase();
    return omit && next && !hexadecimalRegex.test(String.fromCharCode(next)) ? value : value + ";";
}

const decimalRegex = /\d/;

function toDecimal(code, next, omit) {
    const value = "&#" + String(code);
    return omit && next && !decimalRegex.test(String.fromCharCode(next)) ? value : value + ";";
}

const characterEntitiesLegacy = [
    "AElig",
    "AMP",
    "Aacute",
    "Acirc",
    "Agrave",
    "Aring",
    "Atilde",
    "Auml",
    "COPY",
    "Ccedil",
    "ETH",
    "Eacute",
    "Ecirc",
    "Egrave",
    "Euml",
    "GT",
    "Iacute",
    "Icirc",
    "Igrave",
    "Iuml",
    "LT",
    "Ntilde",
    "Oacute",
    "Ocirc",
    "Ograve",
    "Oslash",
    "Otilde",
    "Ouml",
    "QUOT",
    "REG",
    "THORN",
    "Uacute",
    "Ucirc",
    "Ugrave",
    "Uuml",
    "Yacute",
    "aacute",
    "acirc",
    "acute",
    "aelig",
    "agrave",
    "amp",
    "aring",
    "atilde",
    "auml",
    "brvbar",
    "ccedil",
    "cedil",
    "cent",
    "copy",
    "curren",
    "deg",
    "divide",
    "eacute",
    "ecirc",
    "egrave",
    "eth",
    "euml",
    "frac12",
    "frac14",
    "frac34",
    "gt",
    "iacute",
    "icirc",
    "iexcl",
    "igrave",
    "iquest",
    "iuml",
    "laquo",
    "lt",
    "macr",
    "micro",
    "middot",
    "nbsp",
    "not",
    "ntilde",
    "oacute",
    "ocirc",
    "ograve",
    "ordf",
    "ordm",
    "oslash",
    "otilde",
    "ouml",
    "para",
    "plusmn",
    "pound",
    "quot",
    "raquo",
    "reg",
    "sect",
    "shy",
    "sup1",
    "sup2",
    "sup3",
    "szlig",
    "thorn",
    "times",
    "uacute",
    "ucirc",
    "ugrave",
    "uml",
    "uuml",
    "yacute",
    "yen",
    "yuml"
];
const characterEntitiesHtml4 = {
    nbsp: " ",
    iexcl: "¡",
    cent: "¢",
    pound: "£",
    curren: "¤",
    yen: "¥",
    brvbar: "¦",
    sect: "§",
    uml: "¨",
    copy: "©",
    ordf: "ª",
    laquo: "«",
    not: "¬",
    shy: "­",
    reg: "®",
    macr: "¯",
    deg: "°",
    plusmn: "±",
    sup2: "²",
    sup3: "³",
    acute: "´",
    micro: "µ",
    para: "¶",
    middot: "·",
    cedil: "¸",
    sup1: "¹",
    ordm: "º",
    raquo: "»",
    frac14: "¼",
    frac12: "½",
    frac34: "¾",
    iquest: "¿",
    Agrave: "À",
    Aacute: "Á",
    Acirc: "Â",
    Atilde: "Ã",
    Auml: "Ä",
    Aring: "Å",
    AElig: "Æ",
    Ccedil: "Ç",
    Egrave: "È",
    Eacute: "É",
    Ecirc: "Ê",
    Euml: "Ë",
    Igrave: "Ì",
    Iacute: "Í",
    Icirc: "Î",
    Iuml: "Ï",
    ETH: "Ð",
    Ntilde: "Ñ",
    Ograve: "Ò",
    Oacute: "Ó",
    Ocirc: "Ô",
    Otilde: "Õ",
    Ouml: "Ö",
    times: "×",
    Oslash: "Ø",
    Ugrave: "Ù",
    Uacute: "Ú",
    Ucirc: "Û",
    Uuml: "Ü",
    Yacute: "Ý",
    THORN: "Þ",
    szlig: "ß",
    agrave: "à",
    aacute: "á",
    acirc: "â",
    atilde: "ã",
    auml: "ä",
    aring: "å",
    aelig: "æ",
    ccedil: "ç",
    egrave: "è",
    eacute: "é",
    ecirc: "ê",
    euml: "ë",
    igrave: "ì",
    iacute: "í",
    icirc: "î",
    iuml: "ï",
    eth: "ð",
    ntilde: "ñ",
    ograve: "ò",
    oacute: "ó",
    ocirc: "ô",
    otilde: "õ",
    ouml: "ö",
    divide: "÷",
    oslash: "ø",
    ugrave: "ù",
    uacute: "ú",
    ucirc: "û",
    uuml: "ü",
    yacute: "ý",
    thorn: "þ",
    yuml: "ÿ",
    fnof: "ƒ",
    Alpha: "Α",
    Beta: "Β",
    Gamma: "Γ",
    Delta: "Δ",
    Epsilon: "Ε",
    Zeta: "Ζ",
    Eta: "Η",
    Theta: "Θ",
    Iota: "Ι",
    Kappa: "Κ",
    Lambda: "Λ",
    Mu: "Μ",
    Nu: "Ν",
    Xi: "Ξ",
    Omicron: "Ο",
    Pi: "Π",
    Rho: "Ρ",
    Sigma: "Σ",
    Tau: "Τ",
    Upsilon: "Υ",
    Phi: "Φ",
    Chi: "Χ",
    Psi: "Ψ",
    Omega: "Ω",
    alpha: "α",
    beta: "β",
    gamma: "γ",
    delta: "δ",
    epsilon: "ε",
    zeta: "ζ",
    eta: "η",
    theta: "θ",
    iota: "ι",
    kappa: "κ",
    lambda: "λ",
    mu: "μ",
    nu: "ν",
    xi: "ξ",
    omicron: "ο",
    pi: "π",
    rho: "ρ",
    sigmaf: "ς",
    sigma: "σ",
    tau: "τ",
    upsilon: "υ",
    phi: "φ",
    chi: "χ",
    psi: "ψ",
    omega: "ω",
    thetasym: "ϑ",
    upsih: "ϒ",
    piv: "ϖ",
    bull: "•",
    hellip: "…",
    prime: "′",
    Prime: "″",
    oline: "‾",
    frasl: "⁄",
    weierp: "℘",
    image: "ℑ",
    real: "ℜ",
    trade: "™",
    alefsym: "ℵ",
    larr: "←",
    uarr: "↑",
    rarr: "→",
    darr: "↓",
    harr: "↔",
    crarr: "↵",
    lArr: "⇐",
    uArr: "⇑",
    rArr: "⇒",
    dArr: "⇓",
    hArr: "⇔",
    forall: "∀",
    part: "∂",
    exist: "∃",
    empty: "∅",
    nabla: "∇",
    isin: "∈",
    notin: "∉",
    ni: "∋",
    prod: "∏",
    sum: "∑",
    minus: "−",
    lowast: "∗",
    radic: "√",
    prop: "∝",
    infin: "∞",
    ang: "∠",
    and: "∧",
    or: "∨",
    cap: "∩",
    cup: "∪",
    int: "∫",
    there4: "∴",
    sim: "∼",
    cong: "≅",
    asymp: "≈",
    ne: "≠",
    equiv: "≡",
    le: "≤",
    ge: "≥",
    sub: "⊂",
    sup: "⊃",
    nsub: "⊄",
    sube: "⊆",
    supe: "⊇",
    oplus: "⊕",
    otimes: "⊗",
    perp: "⊥",
    sdot: "⋅",
    lceil: "⌈",
    rceil: "⌉",
    lfloor: "⌊",
    rfloor: "⌋",
    lang: "〈",
    rang: "〉",
    loz: "◊",
    spades: "♠",
    clubs: "♣",
    hearts: "♥",
    diams: "♦",
    quot: '"',
    amp: "&",
    lt: "<",
    gt: ">",
    OElig: "Œ",
    oelig: "œ",
    Scaron: "Š",
    scaron: "š",
    Yuml: "Ÿ",
    circ: "ˆ",
    tilde: "˜",
    ensp: " ",
    emsp: " ",
    thinsp: " ",
    zwnj: "‌",
    zwj: "‍",
    lrm: "‎",
    rlm: "‏",
    ndash: "–",
    mdash: "—",
    lsquo: "‘",
    rsquo: "’",
    sbquo: "‚",
    ldquo: "“",
    rdquo: "”",
    bdquo: "„",
    dagger: "†",
    Dagger: "‡",
    permil: "‰",
    lsaquo: "‹",
    rsaquo: "›",
    euro: "€"
};
const dangerous = [
    "cent",
    "copy",
    "divide",
    "gt",
    "lt",
    "not",
    "para",
    "times"
];
const own$1 = {}.hasOwnProperty;
const characters = {};
let key;
for (key in characterEntitiesHtml4) {
    if (own$1.call(characterEntitiesHtml4, key)) {
        characters[characterEntitiesHtml4[key]] = key;
    }
}
const notAlphanumericRegex = /[^\dA-Za-z]/;

function toNamed(code, next, omit, attribute) {
    const character = String.fromCharCode(code);
    if (own$1.call(characters, character)) {
        const name = characters[character];
        const value = "&" + name;
        if (omit && characterEntitiesLegacy.includes(name) && !dangerous.includes(name) && (!attribute || next && next !== 61 && notAlphanumericRegex.test(String.fromCharCode(next)))) {
            return value;
        }
        return value + ";";
    }
    return "";
}

function formatSmart(code, next, options) {
    let numeric = toHexadecimal(code, next, options.omitOptionalSemicolons);
    let named;
    if (options.useNamedReferences || options.useShortestReferences) {
        named = toNamed(
            code,
            next,
            options.omitOptionalSemicolons,
            options.attribute
        );
    }
    if ((options.useShortestReferences || !named) && options.useShortestReferences) {
        const decimal = toDecimal(code, next, options.omitOptionalSemicolons);
        if (decimal.length < numeric.length) {
            numeric = decimal;
        }
    }
    return named && (!options.useShortestReferences || named.length < numeric.length) ? named : numeric;
}

function stringifyEntities(value, options) {
    return core(value, Object.assign({format: formatSmart}, options));
}

const htmlCommentRegex = /^>|^->|<!--|-->|--!>|<!-$/g;
const bogusCommentEntitySubset = [">"];
const commentEntitySubset = ["<", ">"];

function comment(node, _1, _2, state) {
    return state.settings.bogusComments ? "<?" + stringifyEntities(
        node.value,
        Object.assign({}, state.settings.characterReferences, {
            subset: bogusCommentEntitySubset
        })
    ) + ">" : "<!--" + node.value.replace(htmlCommentRegex, encode) + "-->";

    function encode($0) {
        return stringifyEntities(
            $0,
            Object.assign({}, state.settings.characterReferences, {
                subset: commentEntitySubset
            })
        );
    }
}

function doctype(_1, _2, _3, state) {
    return "<!" + (state.settings.upperDoctype ? "DOCTYPE" : "doctype") + (state.settings.tightDoctype ? "" : " ") + "html>";
}

function ccount(value, character) {
    const source = String(value);
    if (typeof character !== "string") {
        throw new TypeError("Expected character");
    }
    let count = 0;
    let index = source.indexOf(character);
    while (index !== -1) {
        count++;
        index = source.indexOf(character, index + character.length);
    }
    return count;
}

function stringify$2(values, options) {
    const settings = options || {};
    const input = values[values.length - 1] === "" ? [...values, ""] : values;
    return input.join(
        (settings.padRight ? " " : "") + "," + (settings.padLeft === false ? "" : " ")
    ).trim();
}

function stringify$1(values) {
    return values.join(" ").trim();
}

const re = /[ \t\n\f\r]/g;

function whitespace(thing) {
    return typeof thing === "object" ? thing.type === "text" ? empty(thing.value) : false : empty(thing);
}

function empty(value) {
    return value.replace(re, "") === "";
}

const siblingAfter = siblings(1);
const siblingBefore = siblings(-1);
const emptyChildren$1 = [];

function siblings(increment2) {
    return sibling;

    function sibling(parent, index, includeWhitespace) {
        const siblings2 = parent ? parent.children : emptyChildren$1;
        let offset = (index || 0) + increment2;
        let next = siblings2[offset];
        if (!includeWhitespace) {
            while (next && whitespace(next)) {
                offset += increment2;
                next = siblings2[offset];
            }
        }
        return next;
    }
}

const own = {}.hasOwnProperty;

function omission(handlers) {
    return omit;

    function omit(node, index, parent) {
        return own.call(handlers, node.tagName) && handlers[node.tagName](node, index, parent);
    }
}

const closing = omission({
    body: body$1,
    caption: headOrColgroupOrCaption,
    colgroup: headOrColgroupOrCaption,
    dd,
    dt,
    head: headOrColgroupOrCaption,
    html: html$1,
    li,
    optgroup,
    option,
    p,
    rp: rubyElement,
    rt: rubyElement,
    tbody: tbody$1,
    td: cells,
    tfoot,
    th: cells,
    thead,
    tr
});

function headOrColgroupOrCaption(_, index, parent) {
    const next = siblingAfter(parent, index, true);
    return !next || next.type !== "comment" && !(next.type === "text" && whitespace(next.value.charAt(0)));
}

function html$1(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type !== "comment";
}

function body$1(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type !== "comment";
}

function p(_, index, parent) {
    const next = siblingAfter(parent, index);
    return next ? next.type === "element" && (next.tagName === "address" || next.tagName === "article" || next.tagName === "aside" || next.tagName === "blockquote" || next.tagName === "details" || next.tagName === "div" || next.tagName === "dl" || next.tagName === "fieldset" || next.tagName === "figcaption" || next.tagName === "figure" || next.tagName === "footer" || next.tagName === "form" || next.tagName === "h1" || next.tagName === "h2" || next.tagName === "h3" || next.tagName === "h4" || next.tagName === "h5" || next.tagName === "h6" || next.tagName === "header" || next.tagName === "hgroup" || next.tagName === "hr" || next.tagName === "main" || next.tagName === "menu" || next.tagName === "nav" || next.tagName === "ol" || next.tagName === "p" || next.tagName === "pre" || next.tagName === "section" || next.tagName === "table" || next.tagName === "ul") : !parent || // Confusing parent.
        !(parent.type === "element" && (parent.tagName === "a" || parent.tagName === "audio" || parent.tagName === "del" || parent.tagName === "ins" || parent.tagName === "map" || parent.tagName === "noscript" || parent.tagName === "video"));
}

function li(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && next.tagName === "li";
}

function dt(_, index, parent) {
    const next = siblingAfter(parent, index);
    return Boolean(
        next && next.type === "element" && (next.tagName === "dt" || next.tagName === "dd")
    );
}

function dd(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && (next.tagName === "dt" || next.tagName === "dd");
}

function rubyElement(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && (next.tagName === "rp" || next.tagName === "rt");
}

function optgroup(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && next.tagName === "optgroup";
}

function option(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && (next.tagName === "option" || next.tagName === "optgroup");
}

function thead(_, index, parent) {
    const next = siblingAfter(parent, index);
    return Boolean(
        next && next.type === "element" && (next.tagName === "tbody" || next.tagName === "tfoot")
    );
}

function tbody$1(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && (next.tagName === "tbody" || next.tagName === "tfoot");
}

function tfoot(_, index, parent) {
    return !siblingAfter(parent, index);
}

function tr(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && next.tagName === "tr";
}

function cells(_, index, parent) {
    const next = siblingAfter(parent, index);
    return !next || next.type === "element" && (next.tagName === "td" || next.tagName === "th");
}

const opening = omission({
    body,
    colgroup,
    head,
    html,
    tbody
});

function html(node) {
    const head2 = siblingAfter(node, -1);
    return !head2 || head2.type !== "comment";
}

function head(node) {
    const seen = /* @__PURE__ */ new Set();
    for (const child2 of node.children) {
        if (child2.type === "element" && (child2.tagName === "base" || child2.tagName === "title")) {
            if (seen.has(child2.tagName)) return false;
            seen.add(child2.tagName);
        }
    }
    const child = node.children[0];
    return !child || child.type === "element";
}

function body(node) {
    const head2 = siblingAfter(node, -1, true);
    return !head2 || head2.type !== "comment" && !(head2.type === "text" && whitespace(head2.value.charAt(0))) && !(head2.type === "element" && (head2.tagName === "meta" || head2.tagName === "link" || head2.tagName === "script" || head2.tagName === "style" || head2.tagName === "template"));
}

function colgroup(node, index, parent) {
    const previous = siblingBefore(parent, index);
    const head2 = siblingAfter(node, -1, true);
    if (parent && previous && previous.type === "element" && previous.tagName === "colgroup" && closing(previous, parent.children.indexOf(previous), parent)) {
        return false;
    }
    return Boolean(head2 && head2.type === "element" && head2.tagName === "col");
}

function tbody(node, index, parent) {
    const previous = siblingBefore(parent, index);
    const head2 = siblingAfter(node, -1);
    if (parent && previous && previous.type === "element" && (previous.tagName === "thead" || previous.tagName === "tbody") && closing(previous, parent.children.indexOf(previous), parent)) {
        return false;
    }
    return Boolean(head2 && head2.type === "element" && head2.tagName === "tr");
}

const constants = {
    // See: <https://html.spec.whatwg.org/#attribute-name-state>.
    name: [
        ["	\n\f\r &/=>".split(""), "	\n\f\r \"&'/=>`".split("")],
        ["\0	\n\f\r \"&'/<=>".split(""), "\0	\n\f\r \"&'/<=>`".split("")]
    ],
    // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.
    unquoted: [
        ["	\n\f\r &>".split(""), "\0	\n\f\r \"&'<=>`".split("")],
        ["\0	\n\f\r \"&'<=>`".split(""), "\0	\n\f\r \"&'<=>`".split("")]
    ],
    // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.
    single: [
        ["&'".split(""), "\"&'`".split("")],
        ["\0&'".split(""), "\0\"&'`".split("")]
    ],
    // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.
    double: [
        ['"&'.split(""), "\"&'`".split("")],
        ['\0"&'.split(""), "\0\"&'`".split("")]
    ]
};

function element(node, index, parent, state) {
    const schema = state.schema;
    const omit = schema.space === "svg" ? false : state.settings.omitOptionalTags;
    let selfClosing = schema.space === "svg" ? state.settings.closeEmptyElements : state.settings.voids.includes(node.tagName.toLowerCase());
    const parts = [];
    let last;
    if (schema.space === "html" && node.tagName === "svg") {
        state.schema = svg;
    }
    const attributes = serializeAttributes(state, node.properties);
    const content = state.all(
        schema.space === "html" && node.tagName === "template" ? node.content : node
    );
    state.schema = schema;
    if (content) selfClosing = false;
    if (attributes || !omit || !opening(node, index, parent)) {
        parts.push("<", node.tagName, attributes ? " " + attributes : "");
        if (selfClosing && (schema.space === "svg" || state.settings.closeSelfClosing)) {
            last = attributes.charAt(attributes.length - 1);
            if (!state.settings.tightSelfClosing || last === "/" || last && last !== '"' && last !== "'") {
                parts.push(" ");
            }
            parts.push("/");
        }
        parts.push(">");
    }
    parts.push(content);
    if (!selfClosing && (!omit || !closing(node, index, parent))) {
        parts.push("</" + node.tagName + ">");
    }
    return parts.join("");
}

function serializeAttributes(state, properties) {
    const values = [];
    let index = -1;
    let key2;
    if (properties) {
        for (key2 in properties) {
            if (properties[key2] !== null && properties[key2] !== void 0) {
                const value = serializeAttribute(state, key2, properties[key2]);
                if (value) values.push(value);
            }
        }
    }
    while (++index < values.length) {
        const last = state.settings.tightAttributes ? values[index].charAt(values[index].length - 1) : void 0;
        if (index !== values.length - 1 && last !== '"' && last !== "'") {
            values[index] += " ";
        }
    }
    return values.join("");
}

function serializeAttribute(state, key2, value) {
    const info = find(state.schema, key2);
    const x = state.settings.allowParseErrors && state.schema.space === "html" ? 0 : 1;
    const y = state.settings.allowDangerousCharacters ? 0 : 1;
    let quote = state.quote;
    let result;
    if (info.overloadedBoolean && (value === info.attribute || value === "")) {
        value = true;
    } else if ((info.boolean || info.overloadedBoolean) && (typeof value !== "string" || value === info.attribute || value === "")) {
        value = Boolean(value);
    }
    if (value === null || value === void 0 || value === false || typeof value === "number" && Number.isNaN(value)) {
        return "";
    }
    const name = stringifyEntities(
        info.attribute,
        Object.assign({}, state.settings.characterReferences, {
            // Always encode without parse errors in non-HTML.
            subset: constants.name[x][y]
        })
    );
    if (value === true) return name;
    value = Array.isArray(value) ? (info.commaSeparated ? stringify$2 : stringify$1)(value, {
        padLeft: !state.settings.tightCommaSeparatedLists
    }) : String(value);
    if (state.settings.collapseEmptyAttributes && !value) return name;
    if (state.settings.preferUnquoted) {
        result = stringifyEntities(
            value,
            Object.assign({}, state.settings.characterReferences, {
                attribute: true,
                subset: constants.unquoted[x][y]
            })
        );
    }
    if (result !== value) {
        if (state.settings.quoteSmart && ccount(value, quote) > ccount(value, state.alternative)) {
            quote = state.alternative;
        }
        result = quote + stringifyEntities(
            value,
            Object.assign({}, state.settings.characterReferences, {
                // Always encode without parse errors in non-HTML.
                subset: (quote === "'" ? constants.single : constants.double)[x][y],
                attribute: true
            })
        ) + quote;
    }
    return name + (result ? "=" + result : result);
}

const textEntitySubset = ["<", "&"];

function text(node, _, parent, state) {
    return parent && parent.type === "element" && (parent.tagName === "script" || parent.tagName === "style") ? node.value : stringifyEntities(
        node.value,
        Object.assign({}, state.settings.characterReferences, {
            subset: textEntitySubset
        })
    );
}

function raw(node, index, parent, state) {
    return state.settings.allowDangerousHtml ? node.value : text(node, index, parent, state);
}

function root(node, _1, _2, state) {
    return state.all(node);
}

const handle = zwitch("type", {
    invalid,
    unknown,
    handlers: {comment, doctype, element, raw, root, text}
});

function invalid(node) {
    throw new Error("Expected node, not `" + node + "`");
}

function unknown(node_) {
    const node = (
        /** @type {Nodes} */
        node_
    );
    throw new Error("Cannot compile unknown node `" + node.type + "`");
}

const emptyOptions = {};
const emptyCharacterReferences = {};
const emptyChildren = [];

function toHtml(tree, options) {
    const options_ = emptyOptions;
    const quote = options_.quote || '"';
    const alternative = quote === '"' ? "'" : '"';
    if (quote !== '"' && quote !== "'") {
        throw new Error("Invalid quote `" + quote + "`, expected `'` or `\"`");
    }
    const state = {
        one,
        all,
        settings: {
            omitOptionalTags: options_.omitOptionalTags || false,
            allowParseErrors: options_.allowParseErrors || false,
            allowDangerousCharacters: options_.allowDangerousCharacters || false,
            quoteSmart: options_.quoteSmart || false,
            preferUnquoted: options_.preferUnquoted || false,
            tightAttributes: options_.tightAttributes || false,
            upperDoctype: options_.upperDoctype || false,
            tightDoctype: options_.tightDoctype || false,
            bogusComments: options_.bogusComments || false,
            tightCommaSeparatedLists: options_.tightCommaSeparatedLists || false,
            tightSelfClosing: options_.tightSelfClosing || false,
            collapseEmptyAttributes: options_.collapseEmptyAttributes || false,
            allowDangerousHtml: options_.allowDangerousHtml || false,
            voids: options_.voids || htmlVoidElements,
            characterReferences: options_.characterReferences || emptyCharacterReferences,
            closeSelfClosing: options_.closeSelfClosing || false,
            closeEmptyElements: options_.closeEmptyElements || false
        },
        schema: options_.space === "svg" ? svg : html$2,
        quote,
        alternative
    };
    return state.one(
        Array.isArray(tree) ? {type: "root", children: tree} : tree,
        void 0,
        void 0
    );
}

function one(node, index, parent) {
    return handle(node, index, parent, this);
}

function all(parent) {
    const results = [];
    const children = parent && parent.children || emptyChildren;
    let index = -1;
    while (++index < children.length) {
        results[index] = this.one(children[index], index, parent);
    }
    return results.join("");
}

function toArray(x) {
    return Array.isArray(x) ? x : [x];
}

function splitLines(code, preserveEnding = false) {
    var _a2;
    const parts = code.split(/(\r?\n)/g);
    let index = 0;
    const lines = [];
    for (let i = 0; i < parts.length; i += 2) {
        const line = preserveEnding ? parts[i] + (parts[i + 1] || "") : parts[i];
        lines.push([line, index]);
        index += parts[i].length;
        index += ((_a2 = parts[i + 1]) == null ? void 0 : _a2.length) || 0;
    }
    return lines;
}

function isPlainLang(lang) {
    return !lang || ["plaintext", "txt", "text", "plain"].includes(lang);
}

function isSpecialLang(lang) {
    return lang === "ansi" || isPlainLang(lang);
}

function isNoneTheme(theme) {
    return theme === "none";
}

function isSpecialTheme(theme) {
    return isNoneTheme(theme);
}

function addClassToHast(node, className) {
    var _a2;
    if (!className)
        return node;
    node.properties || (node.properties = {});
    (_a2 = node.properties).class || (_a2.class = []);
    if (typeof node.properties.class === "string")
        node.properties.class = node.properties.class.split(/\s+/g);
    if (!Array.isArray(node.properties.class))
        node.properties.class = [];
    const targets = Array.isArray(className) ? className : className.split(/\s+/g);
    for (const c of targets) {
        if (c && !node.properties.class.includes(c))
            node.properties.class.push(c);
    }
    return node;
}

function splitToken(token, offsets) {
    let lastOffset = 0;
    const tokens = [];
    for (const offset of offsets) {
        if (offset > lastOffset) {
            tokens.push({
                ...token,
                content: token.content.slice(lastOffset, offset),
                offset: token.offset + lastOffset
            });
        }
        lastOffset = offset;
    }
    if (lastOffset < token.content.length) {
        tokens.push({
            ...token,
            content: token.content.slice(lastOffset),
            offset: token.offset + lastOffset
        });
    }
    return tokens;
}

function splitTokens(tokens, breakpoints) {
    const sorted = Array.from(breakpoints instanceof Set ? breakpoints : new Set(breakpoints)).sort((a, b) => a - b);
    if (!sorted.length)
        return tokens;
    return tokens.map((line) => {
        return line.flatMap((token) => {
            const breakpointsInToken = sorted.filter((i) => token.offset < i && i < token.offset + token.content.length).map((i) => i - token.offset).sort((a, b) => a - b);
            if (!breakpointsInToken.length)
                return token;
            return splitToken(token, breakpointsInToken);
        });
    });
}

async function normalizeGetter(p2) {
    return Promise.resolve(typeof p2 === "function" ? p2() : p2).then((r) => r.default || r);
}

function resolveColorReplacements(theme, options) {
    const replacements = typeof theme === "string" ? {} : {...theme.colorReplacements};
    const themeName = typeof theme === "string" ? theme : theme.name;
    for (const [key2, value] of Object.entries((options == null ? void 0 : options.colorReplacements) || {})) {
        if (typeof value === "string")
            replacements[key2] = value;
        else if (key2 === themeName)
            Object.assign(replacements, value);
    }
    return replacements;
}

function applyColorReplacements(color, replacements) {
    if (!color)
        return color;
    return (replacements == null ? void 0 : replacements[color == null ? void 0 : color.toLowerCase()]) || color;
}

function getTokenStyleObject(token) {
    const styles = {};
    if (token.color)
        styles.color = token.color;
    if (token.bgColor)
        styles["background-color"] = token.bgColor;
    if (token.fontStyle) {
        if (token.fontStyle & FontStyle.Italic)
            styles["font-style"] = "italic";
        if (token.fontStyle & FontStyle.Bold)
            styles["font-weight"] = "bold";
        if (token.fontStyle & FontStyle.Underline)
            styles["text-decoration"] = "underline";
    }
    return styles;
}

function stringifyTokenStyle(token) {
    if (typeof token === "string")
        return token;
    return Object.entries(token).map(([key2, value]) => "".concat(key2, ":").concat(value)).join(";");
}

function createPositionConverter(code) {
    const lines = splitLines(code, true).map(([line]) => line);

    function indexToPos(index) {
        if (index === code.length) {
            return {
                line: lines.length - 1,
                character: lines[lines.length - 1].length
            };
        }
        let character = index;
        let line = 0;
        for (const lineText of lines) {
            if (character < lineText.length)
                break;
            character -= lineText.length;
            line++;
        }
        return {line, character};
    }

    function posToIndex(line, character) {
        let index = 0;
        for (let i = 0; i < line; i++)
            index += lines[i].length;
        index += character;
        return index;
    }

    return {
        lines,
        indexToPos,
        posToIndex
    };
}

class ShikiError3 extends Error {
    constructor(message) {
        super(message);
        this.name = "ShikiError";
    }
}

const _grammarStateMap = /* @__PURE__ */ new WeakMap();

function setLastGrammarStateToMap(keys, state) {
    _grammarStateMap.set(keys, state);
}

function getLastGrammarStateFromMap(keys) {
    return _grammarStateMap.get(keys);
}

class GrammarState {
    constructor(...args) {
        /**
         * Theme to Stack mapping
         */
        __publicField(this, "_stacks", {});
        __publicField(this, "lang");
        if (args.length === 2) {
            const [stacksMap, lang] = args;
            this.lang = lang;
            this._stacks = stacksMap;
        } else {
            const [stack, lang, theme] = args;
            this.lang = lang;
            this._stacks = {[theme]: stack};
        }
    }

    get themes() {
        return Object.keys(this._stacks);
    }

    get theme() {
        return this.themes[0];
    }

    get _stack() {
        return this._stacks[this.theme];
    }

    /**
     * @deprecated use `getScopes` instead
     */
    get scopes() {
        warnDeprecated("GrammarState.scopes is deprecated, use GrammarState.getScopes() instead");
        return getScopes(this._stacks[this.theme]);
    }

    /**
     * Static method to create a initial grammar state.
     */
    static initial(lang, themes) {
        return new GrammarState(
            Object.fromEntries(toArray(themes).map((theme) => [theme, INITIAL])),
            lang
        );
    }

    /**
     * Get the internal stack object.
     * @internal
     */
    getInternalStack(theme = this.theme) {
        return this._stacks[theme];
    }

    getScopes(theme = this.theme) {
        return getScopes(this._stacks[theme]);
    }

    toJSON() {
        return {
            lang: this.lang,
            theme: this.theme,
            themes: this.themes,
            scopes: this.getScopes()
        };
    }
}

function getScopes(stack) {
    const scopes = [];
    const visited = /* @__PURE__ */ new Set();

    function pushScope(stack2) {
        var _a2;
        if (visited.has(stack2))
            return;
        visited.add(stack2);
        const name = (_a2 = stack2 == null ? void 0 : stack2.nameScopesList) == null ? void 0 : _a2.scopeName;
        if (name)
            scopes.push(name);
        if (stack2.parent)
            pushScope(stack2.parent);
    }

    pushScope(stack);
    return scopes;
}

function getGrammarStack(state, theme) {
    if (!(state instanceof GrammarState))
        throw new ShikiError3("Invalid grammar state");
    return state.getInternalStack(theme);
}

function transformerDecorations() {
    const map = /* @__PURE__ */ new WeakMap();

    function getContext(shiki2) {
        if (!map.has(shiki2.meta)) {
            let normalizePosition = function (p2) {
                if (typeof p2 === "number") {
                    if (p2 < 0 || p2 > shiki2.source.length)
                        throw new ShikiError3("Invalid decoration offset: ".concat(p2, ". Code length: ").concat(shiki2.source.length));
                    return {
                        ...converter.indexToPos(p2),
                        offset: p2
                    };
                } else {
                    const line = converter.lines[p2.line];
                    if (line === void 0)
                        throw new ShikiError3("Invalid decoration position ".concat(JSON.stringify(p2), ". Lines length: ").concat(converter.lines.length));
                    if (p2.character < 0 || p2.character > line.length)
                        throw new ShikiError3("Invalid decoration position ".concat(JSON.stringify(p2), ". Line ").concat(p2.line, " length: ").concat(line.length));
                    return {
                        ...p2,
                        offset: converter.posToIndex(p2.line, p2.character)
                    };
                }
            };
            const converter = createPositionConverter(shiki2.source);
            const decorations2 = (shiki2.options.decorations || []).map((d) => ({
                ...d,
                start: normalizePosition(d.start),
                end: normalizePosition(d.end)
            }));
            verifyIntersections(decorations2);
            map.set(shiki2.meta, {
                decorations: decorations2,
                converter,
                source: shiki2.source
            });
        }
        return map.get(shiki2.meta);
    }

    return {
        name: "shiki:decorations",
        tokens(tokens) {
            var _a2;
            if (!((_a2 = this.options.decorations) == null ? void 0 : _a2.length))
                return;
            const ctx = getContext(this);
            const breakpoints = ctx.decorations.flatMap((d) => [d.start.offset, d.end.offset]);
            const splitted = splitTokens(tokens, breakpoints);
            return splitted;
        },
        code(codeEl) {
            var _a2;
            if (!((_a2 = this.options.decorations) == null ? void 0 : _a2.length))
                return;
            const ctx = getContext(this);
            const lines = Array.from(codeEl.children).filter((i) => i.type === "element" && i.tagName === "span");
            if (lines.length !== ctx.converter.lines.length)
                throw new ShikiError3("Number of lines in code element (".concat(lines.length, ") does not match the number of lines in the source (").concat(ctx.converter.lines.length, "). Failed to apply decorations."));

            function applyLineSection(line, start, end, decoration) {
                const lineEl = lines[line];
                let text2 = "";
                let startIndex = -1;
                let endIndex = -1;
                if (start === 0)
                    startIndex = 0;
                if (end === 0)
                    endIndex = 0;
                if (end === Number.POSITIVE_INFINITY)
                    endIndex = lineEl.children.length;
                if (startIndex === -1 || endIndex === -1) {
                    for (let i = 0; i < lineEl.children.length; i++) {
                        text2 += stringify(lineEl.children[i]);
                        if (startIndex === -1 && text2.length === start)
                            startIndex = i + 1;
                        if (endIndex === -1 && text2.length === end)
                            endIndex = i + 1;
                    }
                }
                if (startIndex === -1)
                    throw new ShikiError3("Failed to find start index for decoration ".concat(JSON.stringify(decoration.start)));
                if (endIndex === -1)
                    throw new ShikiError3("Failed to find end index for decoration ".concat(JSON.stringify(decoration.end)));
                const children = lineEl.children.slice(startIndex, endIndex);
                if (!decoration.alwaysWrap && children.length === lineEl.children.length) {
                    applyDecoration(lineEl, decoration, "line");
                } else if (!decoration.alwaysWrap && children.length === 1 && children[0].type === "element") {
                    applyDecoration(children[0], decoration, "token");
                } else {
                    const wrapper = {
                        type: "element",
                        tagName: "span",
                        properties: {},
                        children
                    };
                    applyDecoration(wrapper, decoration, "wrapper");
                    lineEl.children.splice(startIndex, children.length, wrapper);
                }
            }

            function applyLine(line, decoration) {
                lines[line] = applyDecoration(lines[line], decoration, "line");
            }

            function applyDecoration(el, decoration, type) {
                var _a3;
                const properties = decoration.properties || {};
                const transform = decoration.transform || ((i) => i);
                el.tagName = decoration.tagName || "span";
                el.properties = {
                    ...el.properties,
                    ...properties,
                    class: el.properties.class
                };
                if ((_a3 = decoration.properties) == null ? void 0 : _a3.class)
                    addClassToHast(el, decoration.properties.class);
                el = transform(el, type) || el;
                return el;
            }

            const lineApplies = [];
            const sorted = ctx.decorations.sort((a, b) => b.start.offset - a.start.offset || a.end.offset - b.end.offset);
            for (const decoration of sorted) {
                const {start, end} = decoration;
                if (start.line === end.line) {
                    applyLineSection(start.line, start.character, end.character, decoration);
                } else if (start.line < end.line) {
                    applyLineSection(start.line, start.character, Number.POSITIVE_INFINITY, decoration);
                    for (let i = start.line + 1; i < end.line; i++)
                        lineApplies.unshift(() => applyLine(i, decoration));
                    applyLineSection(end.line, 0, end.character, decoration);
                }
            }
            lineApplies.forEach((i) => i());
        }
    };
}

function verifyIntersections(items) {
    for (let i = 0; i < items.length; i++) {
        const foo = items[i];
        if (foo.start.offset > foo.end.offset)
            throw new ShikiError3("Invalid decoration range: ".concat(JSON.stringify(foo.start), " - ").concat(JSON.stringify(foo.end)));
        for (let j = i + 1; j < items.length; j++) {
            const bar = items[j];
            const isFooHasBarStart = foo.start.offset <= bar.start.offset && bar.start.offset < foo.end.offset;
            const isFooHasBarEnd = foo.start.offset < bar.end.offset && bar.end.offset <= foo.end.offset;
            const isBarHasFooStart = bar.start.offset <= foo.start.offset && foo.start.offset < bar.end.offset;
            const isBarHasFooEnd = bar.start.offset < foo.end.offset && foo.end.offset <= bar.end.offset;
            if (isFooHasBarStart || isFooHasBarEnd || isBarHasFooStart || isBarHasFooEnd) {
                if (isFooHasBarStart && isFooHasBarEnd)
                    continue;
                if (isBarHasFooStart && isBarHasFooEnd)
                    continue;
                throw new ShikiError3("Decorations ".concat(JSON.stringify(foo.start), " and ").concat(JSON.stringify(bar.start), " intersect."));
            }
        }
    }
}

function stringify(el) {
    if (el.type === "text")
        return el.value;
    if (el.type === "element")
        return el.children.map(stringify).join("");
    return "";
}

const builtInTransformers = [
    /* @__PURE__ */ transformerDecorations()
];

function getTransformers(options) {
    return [
        ...options.transformers || [],
        ...builtInTransformers
    ];
}

var namedColors = [
    "black",
    "red",
    "green",
    "yellow",
    "blue",
    "magenta",
    "cyan",
    "white",
    "brightBlack",
    "brightRed",
    "brightGreen",
    "brightYellow",
    "brightBlue",
    "brightMagenta",
    "brightCyan",
    "brightWhite"
];
var decorations = {
    1: "bold",
    2: "dim",
    3: "italic",
    4: "underline",
    7: "reverse",
    9: "strikethrough"
};

function findSequence(value, position) {
    const nextEscape = value.indexOf("\x1B[", position);
    if (nextEscape !== -1) {
        const nextClose = value.indexOf("m", nextEscape);
        return {
            sequence: value.substring(nextEscape + 2, nextClose).split(";"),
            startPosition: nextEscape,
            position: nextClose + 1
        };
    }
    return {
        position: value.length
    };
}

function parseColor(sequence, index) {
    let offset = 1;
    const colorMode = sequence[index + offset++];
    let color;
    if (colorMode === "2") {
        const rgb = [
            sequence[index + offset++],
            sequence[index + offset++],
            sequence[index + offset]
        ].map((x) => Number.parseInt(x));
        if (rgb.length === 3 && !rgb.some((x) => Number.isNaN(x))) {
            color = {
                type: "rgb",
                rgb
            };
        }
    } else if (colorMode === "5") {
        const colorIndex = Number.parseInt(sequence[index + offset]);
        if (!Number.isNaN(colorIndex)) {
            color = {type: "table", index: Number(colorIndex)};
        }
    }
    return [offset, color];
}

function parseSequence(sequence) {
    const commands = [];
    for (let i = 0; i < sequence.length; i++) {
        const code = sequence[i];
        const codeInt = Number.parseInt(code);
        if (Number.isNaN(codeInt))
            continue;
        if (codeInt === 0) {
            commands.push({type: "resetAll"});
        } else if (codeInt <= 9) {
            const decoration = decorations[codeInt];
            if (decoration) {
                commands.push({
                    type: "setDecoration",
                    value: decorations[codeInt]
                });
            }
        } else if (codeInt <= 29) {
            const decoration = decorations[codeInt - 20];
            if (decoration) {
                commands.push({
                    type: "resetDecoration",
                    value: decoration
                });
            }
        } else if (codeInt <= 37) {
            commands.push({
                type: "setForegroundColor",
                value: {type: "named", name: namedColors[codeInt - 30]}
            });
        } else if (codeInt === 38) {
            const [offset, color] = parseColor(sequence, i);
            if (color) {
                commands.push({
                    type: "setForegroundColor",
                    value: color
                });
            }
            i += offset;
        } else if (codeInt === 39) {
            commands.push({
                type: "resetForegroundColor"
            });
        } else if (codeInt <= 47) {
            commands.push({
                type: "setBackgroundColor",
                value: {type: "named", name: namedColors[codeInt - 40]}
            });
        } else if (codeInt === 48) {
            const [offset, color] = parseColor(sequence, i);
            if (color) {
                commands.push({
                    type: "setBackgroundColor",
                    value: color
                });
            }
            i += offset;
        } else if (codeInt === 49) {
            commands.push({
                type: "resetBackgroundColor"
            });
        } else if (codeInt >= 90 && codeInt <= 97) {
            commands.push({
                type: "setForegroundColor",
                value: {type: "named", name: namedColors[codeInt - 90 + 8]}
            });
        } else if (codeInt >= 100 && codeInt <= 107) {
            commands.push({
                type: "setBackgroundColor",
                value: {type: "named", name: namedColors[codeInt - 100 + 8]}
            });
        }
    }
    return commands;
}

function createAnsiSequenceParser() {
    let foreground = null;
    let background = null;
    let decorations2 = /* @__PURE__ */ new Set();
    return {
        parse(value) {
            const tokens = [];
            let position = 0;
            do {
                const findResult = findSequence(value, position);
                const text2 = findResult.sequence ? value.substring(position, findResult.startPosition) : value.substring(position);
                if (text2.length > 0) {
                    tokens.push({
                        value: text2,
                        foreground,
                        background,
                        decorations: new Set(decorations2)
                    });
                }
                if (findResult.sequence) {
                    const commands = parseSequence(findResult.sequence);
                    for (const styleToken of commands) {
                        if (styleToken.type === "resetAll") {
                            foreground = null;
                            background = null;
                            decorations2.clear();
                        } else if (styleToken.type === "resetForegroundColor") {
                            foreground = null;
                        } else if (styleToken.type === "resetBackgroundColor") {
                            background = null;
                        } else if (styleToken.type === "resetDecoration") {
                            decorations2.delete(styleToken.value);
                        }
                    }
                    for (const styleToken of commands) {
                        if (styleToken.type === "setForegroundColor") {
                            foreground = styleToken.value;
                        } else if (styleToken.type === "setBackgroundColor") {
                            background = styleToken.value;
                        } else if (styleToken.type === "setDecoration") {
                            decorations2.add(styleToken.value);
                        }
                    }
                }
                position = findResult.position;
            } while (position < value.length);
            return tokens;
        }
    };
}

var defaultNamedColorsMap = {
    black: "#000000",
    red: "#bb0000",
    green: "#00bb00",
    yellow: "#bbbb00",
    blue: "#0000bb",
    magenta: "#ff00ff",
    cyan: "#00bbbb",
    white: "#eeeeee",
    brightBlack: "#555555",
    brightRed: "#ff5555",
    brightGreen: "#00ff00",
    brightYellow: "#ffff55",
    brightBlue: "#5555ff",
    brightMagenta: "#ff55ff",
    brightCyan: "#55ffff",
    brightWhite: "#ffffff"
};

function createColorPalette(namedColorsMap = defaultNamedColorsMap) {
    function namedColor(name) {
        return namedColorsMap[name];
    }

    function rgbColor(rgb) {
        return "#".concat(rgb.map((x) => Math.max(0, Math.min(x, 255)).toString(16).padStart(2, "0")).join(""));
    }

    let colorTable;

    function getColorTable() {
        if (colorTable) {
            return colorTable;
        }
        colorTable = [];
        for (let i = 0; i < namedColors.length; i++) {
            colorTable.push(namedColor(namedColors[i]));
        }
        let levels = [0, 95, 135, 175, 215, 255];
        for (let r = 0; r < 6; r++) {
            for (let g = 0; g < 6; g++) {
                for (let b = 0; b < 6; b++) {
                    colorTable.push(rgbColor([levels[r], levels[g], levels[b]]));
                }
            }
        }
        let level = 8;
        for (let i = 0; i < 24; i++, level += 10) {
            colorTable.push(rgbColor([level, level, level]));
        }
        return colorTable;
    }

    function tableColor(index) {
        return getColorTable()[index];
    }

    function value(color) {
        switch (color.type) {
            case "named":
                return namedColor(color.name);
            case "rgb":
                return rgbColor(color.rgb);
            case "table":
                return tableColor(color.index);
        }
    }

    return {
        value
    };
}

function tokenizeAnsiWithTheme(theme, fileContents, options) {
    const colorReplacements = resolveColorReplacements(theme, options);
    const lines = splitLines(fileContents);
    const colorPalette = createColorPalette(
        Object.fromEntries(
            namedColors.map((name) => {
                var _a2;
                return [
                    name,
                    (_a2 = theme.colors) == null ? void 0 : _a2["terminal.ansi".concat(name[0].toUpperCase()).concat(name.substring(1))]
                ];
            })
        )
    );
    const parser = createAnsiSequenceParser();
    return lines.map(
        (line) => parser.parse(line[0]).map((token) => {
            let color;
            let bgColor;
            if (token.decorations.has("reverse")) {
                color = token.background ? colorPalette.value(token.background) : theme.bg;
                bgColor = token.foreground ? colorPalette.value(token.foreground) : theme.fg;
            } else {
                color = token.foreground ? colorPalette.value(token.foreground) : theme.fg;
                bgColor = token.background ? colorPalette.value(token.background) : void 0;
            }
            color = applyColorReplacements(color, colorReplacements);
            bgColor = applyColorReplacements(bgColor, colorReplacements);
            if (token.decorations.has("dim"))
                color = dimColor(color);
            let fontStyle = FontStyle.None;
            if (token.decorations.has("bold"))
                fontStyle |= FontStyle.Bold;
            if (token.decorations.has("italic"))
                fontStyle |= FontStyle.Italic;
            if (token.decorations.has("underline"))
                fontStyle |= FontStyle.Underline;
            return {
                content: token.value,
                offset: line[1],
                // TODO: more accurate offset? might need to fork ansi-sequence-parser
                color,
                bgColor,
                fontStyle
            };
        })
    );
}

function dimColor(color) {
    const hexMatch = color.match(/#([0-9a-f]{3})([0-9a-f]{3})?([0-9a-f]{2})?/);
    if (hexMatch) {
        if (hexMatch[3]) {
            const alpha = Math.round(Number.parseInt(hexMatch[3], 16) / 2).toString(16).padStart(2, "0");
            return "#".concat(hexMatch[1]).concat(hexMatch[2]).concat(alpha);
        } else if (hexMatch[2]) {
            return "#".concat(hexMatch[1]).concat(hexMatch[2], "80");
        } else {
            return "#".concat(Array.from(hexMatch[1]).map((x) => "".concat(x).concat(x)).join(""), "80");
        }
    }
    const cssVarMatch = color.match(/var\((--[\w-]+-ansi-[\w-]+)\)/);
    if (cssVarMatch)
        return "var(".concat(cssVarMatch[1], "-dim)");
    return color;
}

function codeToTokensBase(internal, code, options = {}) {
    const {
        lang = "text",
        theme: themeName = internal.getLoadedThemes()[0]
    } = options;
    if (isPlainLang(lang) || isNoneTheme(themeName))
        return splitLines(code).map((line) => [{content: line[0], offset: line[1]}]);
    const {theme, colorMap} = internal.setTheme(themeName);
    if (lang === "ansi")
        return tokenizeAnsiWithTheme(theme, code, options);
    const _grammar = internal.getLanguage(lang);
    if (options.grammarState) {
        if (options.grammarState.lang !== _grammar.name) {
            throw new ShikiError$2('Grammar state language "'.concat(options.grammarState.lang, '" does not match highlight language "').concat(_grammar.name, '"'));
        }
        if (!options.grammarState.themes.includes(theme.name)) {
            throw new ShikiError$2('Grammar state themes "'.concat(options.grammarState.themes, '" do not contain highlight theme "').concat(theme.name, '"'));
        }
    }
    return tokenizeWithTheme(code, _grammar, theme, colorMap, options);
}

function getLastGrammarState(...args) {
    if (args.length === 2) {
        return getLastGrammarStateFromMap(args[1]);
    }
    const [internal, code, options = {}] = args;
    const {
        lang = "text",
        theme: themeName = internal.getLoadedThemes()[0]
    } = options;
    if (isPlainLang(lang) || isNoneTheme(themeName))
        throw new ShikiError$2("Plain language does not have grammar state");
    if (lang === "ansi")
        throw new ShikiError$2("ANSI language does not have grammar state");
    const {theme, colorMap} = internal.setTheme(themeName);
    const _grammar = internal.getLanguage(lang);
    return new GrammarState(
        _tokenizeWithTheme(code, _grammar, theme, colorMap, options).stateStack,
        _grammar.name,
        theme.name
    );
}

function tokenizeWithTheme(code, grammar, theme, colorMap, options) {
    const result = _tokenizeWithTheme(code, grammar, theme, colorMap, options);
    const grammarState = new GrammarState(
        _tokenizeWithTheme(code, grammar, theme, colorMap, options).stateStack,
        grammar.name,
        theme.name
    );
    setLastGrammarStateToMap(result.tokens, grammarState);
    return result.tokens;
}

function _tokenizeWithTheme(code, grammar, theme, colorMap, options) {
    var _a2;
    const colorReplacements = resolveColorReplacements(theme, options);
    const {
        tokenizeMaxLineLength = 0,
        tokenizeTimeLimit = 500
    } = options;
    const lines = splitLines(code);
    let stateStack = options.grammarState ? (_a2 = getGrammarStack(options.grammarState, theme.name)) != null ? _a2 : INITIAL : options.grammarContextCode != null ? _tokenizeWithTheme(
        options.grammarContextCode,
        grammar,
        theme,
        colorMap,
        {
            ...options,
            grammarState: void 0,
            grammarContextCode: void 0
        }
    ).stateStack : INITIAL;
    let actual = [];
    const final = [];
    for (let i = 0, len = lines.length; i < len; i++) {
        const [line, lineOffset] = lines[i];
        if (line === "") {
            actual = [];
            final.push([]);
            continue;
        }
        if (tokenizeMaxLineLength > 0 && line.length >= tokenizeMaxLineLength) {
            actual = [];
            final.push([{
                content: line,
                offset: lineOffset,
                color: "",
                fontStyle: 0
            }]);
            continue;
        }
        let resultWithScopes;
        let tokensWithScopes;
        let tokensWithScopesIndex;
        if (options.includeExplanation) {
            resultWithScopes = grammar.tokenizeLine(line, stateStack);
            tokensWithScopes = resultWithScopes.tokens;
            tokensWithScopesIndex = 0;
        }
        const result = grammar.tokenizeLine2(line, stateStack, tokenizeTimeLimit);
        const tokensLength = result.tokens.length / 2;
        for (let j = 0; j < tokensLength; j++) {
            const startIndex = result.tokens[2 * j];
            const nextStartIndex = j + 1 < tokensLength ? result.tokens[2 * j + 2] : line.length;
            if (startIndex === nextStartIndex)
                continue;
            const metadata = result.tokens[2 * j + 1];
            const color = applyColorReplacements(
                colorMap[EncodedTokenMetadata.getForeground(metadata)],
                colorReplacements
            );
            const fontStyle = EncodedTokenMetadata.getFontStyle(metadata);
            const token = {
                content: line.substring(startIndex, nextStartIndex),
                offset: lineOffset + startIndex,
                color,
                fontStyle
            };
            if (options.includeExplanation) {
                const themeSettingsSelectors = [];
                if (options.includeExplanation !== "scopeName") {
                    for (const setting of theme.settings) {
                        let selectors;
                        switch (typeof setting.scope) {
                            case "string":
                                selectors = setting.scope.split(/,/).map((scope) => scope.trim());
                                break;
                            case "object":
                                selectors = setting.scope;
                                break;
                            default:
                                continue;
                        }
                        themeSettingsSelectors.push({
                            settings: setting,
                            selectors: selectors.map((selector) => selector.split(/ /))
                        });
                    }
                }
                token.explanation = [];
                let offset = 0;
                while (startIndex + offset < nextStartIndex) {
                    const tokenWithScopes = tokensWithScopes[tokensWithScopesIndex];
                    const tokenWithScopesText = line.substring(
                        tokenWithScopes.startIndex,
                        tokenWithScopes.endIndex
                    );
                    offset += tokenWithScopesText.length;
                    token.explanation.push({
                        content: tokenWithScopesText,
                        scopes: options.includeExplanation === "scopeName" ? explainThemeScopesNameOnly(
                            tokenWithScopes.scopes
                        ) : explainThemeScopesFull(
                            themeSettingsSelectors,
                            tokenWithScopes.scopes
                        )
                    });
                    tokensWithScopesIndex += 1;
                }
            }
            actual.push(token);
        }
        final.push(actual);
        actual = [];
        stateStack = result.ruleStack;
    }
    return {
        tokens: final,
        stateStack
    };
}

function explainThemeScopesNameOnly(scopes) {
    return scopes.map((scope) => ({scopeName: scope}));
}

function explainThemeScopesFull(themeSelectors, scopes) {
    const result = [];
    for (let i = 0, len = scopes.length; i < len; i++) {
        const scope = scopes[i];
        result[i] = {
            scopeName: scope,
            themeMatches: explainThemeScope(themeSelectors, scope, scopes.slice(0, i))
        };
    }
    return result;
}

function matchesOne(selector, scope) {
    return selector === scope || scope.substring(0, selector.length) === selector && scope[selector.length] === ".";
}

function matches(selectors, scope, parentScopes) {
    if (!matchesOne(selectors[selectors.length - 1], scope))
        return false;
    let selectorParentIndex = selectors.length - 2;
    let parentIndex = parentScopes.length - 1;
    while (selectorParentIndex >= 0 && parentIndex >= 0) {
        if (matchesOne(selectors[selectorParentIndex], parentScopes[parentIndex]))
            selectorParentIndex -= 1;
        parentIndex -= 1;
    }
    if (selectorParentIndex === -1)
        return true;
    return false;
}

function explainThemeScope(themeSettingsSelectors, scope, parentScopes) {
    const result = [];
    for (const {selectors, settings} of themeSettingsSelectors) {
        for (const selectorPieces of selectors) {
            if (matches(selectorPieces, scope, parentScopes)) {
                result.push(settings);
                break;
            }
        }
    }
    return result;
}

function codeToTokensWithThemes(internal, code, options) {
    const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({color: i[0], theme: i[1]}));
    const themedTokens = themes.map((t) => {
        const tokens2 = codeToTokensBase(internal, code, {
            ...options,
            theme: t.theme
        });
        const state = getLastGrammarStateFromMap(tokens2);
        const theme = typeof t.theme === "string" ? t.theme : t.theme.name;
        return {
            tokens: tokens2,
            state,
            theme
        };
    });
    const tokens = syncThemesTokenization(
        ...themedTokens.map((i) => i.tokens)
    );
    const mergedTokens = tokens[0].map(
        (line, lineIdx) => line.map((_token, tokenIdx) => {
            const mergedToken = {
                content: _token.content,
                variants: {},
                offset: _token.offset
            };
            if ("includeExplanation" in options && options.includeExplanation) {
                mergedToken.explanation = _token.explanation;
            }
            tokens.forEach((t, themeIdx) => {
                const {
                    content: _,
                    explanation: __,
                    offset: ___,
                    ...styles
                } = t[lineIdx][tokenIdx];
                mergedToken.variants[themes[themeIdx].color] = styles;
            });
            return mergedToken;
        })
    );
    const mergedGrammarState = themedTokens[0].state ? new GrammarState(
        Object.fromEntries(themedTokens.map((s) => {
            var _a2;
            return [s.theme, (_a2 = s.state) == null ? void 0 : _a2.getInternalStack(s.theme)];
        })),
        themedTokens[0].state.lang
    ) : void 0;
    if (mergedGrammarState)
        setLastGrammarStateToMap(mergedTokens, mergedGrammarState);
    return mergedTokens;
}

function syncThemesTokenization(...themes) {
    const outThemes = themes.map(() => []);
    const count = themes.length;
    for (let i = 0; i < themes[0].length; i++) {
        const lines = themes.map((t) => t[i]);
        const outLines = outThemes.map(() => []);
        outThemes.forEach((t, i2) => t.push(outLines[i2]));
        const indexes = lines.map(() => 0);
        const current = lines.map((l) => l[0]);
        while (current.every((t) => t)) {
            const minLength = Math.min(...current.map((t) => t.content.length));
            for (let n = 0; n < count; n++) {
                const token = current[n];
                if (token.content.length === minLength) {
                    outLines[n].push(token);
                    indexes[n] += 1;
                    current[n] = lines[n][indexes[n]];
                } else {
                    outLines[n].push({
                        ...token,
                        content: token.content.slice(0, minLength)
                    });
                    current[n] = {
                        ...token,
                        content: token.content.slice(minLength),
                        offset: token.offset + minLength
                    };
                }
            }
        }
    }
    return outThemes;
}

function codeToTokens(internal, code, options) {
    let bg;
    let fg;
    let tokens;
    let themeName;
    let rootStyle;
    let grammarState;
    if ("themes" in options) {
        const {
            defaultColor = "light",
            cssVariablePrefix = "--shiki-"
        } = options;
        const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({
            color: i[0],
            theme: i[1]
        })).sort((a, b) => a.color === defaultColor ? -1 : b.color === defaultColor ? 1 : 0);
        if (themes.length === 0)
            throw new ShikiError$2("`themes` option must not be empty");
        const themeTokens = codeToTokensWithThemes(
            internal,
            code,
            options
        );
        grammarState = getLastGrammarStateFromMap(themeTokens);
        if (defaultColor && !themes.find((t) => t.color === defaultColor))
            throw new ShikiError$2("`themes` option must contain the defaultColor key `".concat(defaultColor, "`"));
        const themeRegs = themes.map((t) => internal.getTheme(t.theme));
        const themesOrder = themes.map((t) => t.color);
        tokens = themeTokens.map((line) => line.map((token) => mergeToken(token, themesOrder, cssVariablePrefix, defaultColor)));
        if (grammarState)
            setLastGrammarStateToMap(tokens, grammarState);
        const themeColorReplacements = themes.map((t) => resolveColorReplacements(t.theme, options));
        fg = themes.map((t, idx) => (idx === 0 && defaultColor ? "" : "".concat(cssVariablePrefix + t.color, ":")) + (applyColorReplacements(themeRegs[idx].fg, themeColorReplacements[idx]) || "inherit")).join(";");
        bg = themes.map((t, idx) => (idx === 0 && defaultColor ? "" : "".concat(cssVariablePrefix + t.color, "-bg:")) + (applyColorReplacements(themeRegs[idx].bg, themeColorReplacements[idx]) || "inherit")).join(";");
        themeName = "shiki-themes ".concat(themeRegs.map((t) => t.name).join(" "));
        rootStyle = defaultColor ? void 0 : [fg, bg].join(";");
    } else if ("theme" in options) {
        const colorReplacements = resolveColorReplacements(options.theme, options);
        tokens = codeToTokensBase(
            internal,
            code,
            options
        );
        const _theme = internal.getTheme(options.theme);
        bg = applyColorReplacements(_theme.bg, colorReplacements);
        fg = applyColorReplacements(_theme.fg, colorReplacements);
        themeName = _theme.name;
        grammarState = getLastGrammarStateFromMap(tokens);
    } else {
        throw new ShikiError$2("Invalid options, either `theme` or `themes` must be provided");
    }
    return {
        tokens,
        fg,
        bg,
        themeName,
        rootStyle,
        grammarState
    };
}

function mergeToken(merged, variantsOrder, cssVariablePrefix, defaultColor) {
    const token = {
        content: merged.content,
        explanation: merged.explanation,
        offset: merged.offset
    };
    const styles = variantsOrder.map((t) => getTokenStyleObject(merged.variants[t]));
    const styleKeys = new Set(styles.flatMap((t) => Object.keys(t)));
    const mergedStyles = {};
    styles.forEach((cur, idx) => {
        for (const key2 of styleKeys) {
            const value = cur[key2] || "inherit";
            if (idx === 0 && defaultColor) {
                mergedStyles[key2] = value;
            } else {
                const keyName = key2 === "color" ? "" : key2 === "background-color" ? "-bg" : "-".concat(key2);
                const varKey = cssVariablePrefix + variantsOrder[idx] + (key2 === "color" ? "" : keyName);
                mergedStyles[varKey] = value;
            }
        }
    });
    token.htmlStyle = mergedStyles;
    return token;
}

function codeToHast(internal, code, options, transformerContext = {
    meta: {},
    options,
    codeToHast: (_code, _options) => codeToHast(internal, _code, _options),
    codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)
}) {
    var _a2, _b2;
    let input = code;
    for (const transformer of getTransformers(options))
        input = ((_a2 = transformer.preprocess) == null ? void 0 : _a2.call(transformerContext, input, options)) || input;
    let {
        tokens,
        fg,
        bg,
        themeName,
        rootStyle,
        grammarState
    } = codeToTokens(internal, input, options);
    const {
        mergeWhitespaces = true
    } = options;
    if (mergeWhitespaces === true)
        tokens = mergeWhitespaceTokens(tokens);
    else if (mergeWhitespaces === "never")
        tokens = splitWhitespaceTokens(tokens);
    const contextSource = {
        ...transformerContext,
        get source() {
            return input;
        }
    };
    for (const transformer of getTransformers(options))
        tokens = ((_b2 = transformer.tokens) == null ? void 0 : _b2.call(contextSource, tokens)) || tokens;
    return tokensToHast(
        tokens,
        {
            ...options,
            fg,
            bg,
            themeName,
            rootStyle
        },
        contextSource,
        grammarState
    );
}

function tokensToHast(tokens, options, transformerContext, grammarState = getLastGrammarStateFromMap(tokens)) {
    var _a2, _b2, _c;
    const transformers = getTransformers(options);
    const lines = [];
    const root2 = {
        type: "root",
        children: []
    };
    const {
        structure = "classic",
        tabindex = "0"
    } = options;
    let preNode = {
        type: "element",
        tagName: "pre",
        properties: {
            class: "shiki ".concat(options.themeName || ""),
            style: options.rootStyle || "background-color:".concat(options.bg, ";color:").concat(options.fg),
            ...tabindex !== false && tabindex != null ? {
                tabindex: tabindex.toString()
            } : {},
            ...Object.fromEntries(
                Array.from(
                    Object.entries(options.meta || {})
                ).filter(([key2]) => !key2.startsWith("_"))
            )
        },
        children: []
    };
    let codeNode = {
        type: "element",
        tagName: "code",
        properties: {},
        children: lines
    };
    const lineNodes = [];
    const context = {
        ...transformerContext,
        structure,
        addClassToHast,
        get source() {
            return transformerContext.source;
        },
        get tokens() {
            return tokens;
        },
        get options() {
            return options;
        },
        get root() {
            return root2;
        },
        get pre() {
            return preNode;
        },
        get code() {
            return codeNode;
        },
        get lines() {
            return lineNodes;
        }
    };
    tokens.forEach((line, idx) => {
        var _a3, _b3;
        if (idx) {
            if (structure === "inline")
                root2.children.push({type: "element", tagName: "br", properties: {}, children: []});
            else if (structure === "classic")
                lines.push({type: "text", value: "\n"});
        }
        let lineNode = {
            type: "element",
            tagName: "span",
            properties: {class: "line"},
            children: []
        };
        let col = 0;
        for (const token of line) {
            let tokenNode = {
                type: "element",
                tagName: "span",
                properties: {
                    ...token.htmlAttrs
                },
                children: [{type: "text", value: token.content}]
            };
            if (typeof token.htmlStyle === "string")
                warnDeprecated("`htmlStyle` as a string is deprecated. Use an object instead.");
            const style = stringifyTokenStyle(token.htmlStyle || getTokenStyleObject(token));
            if (style)
                tokenNode.properties.style = style;
            for (const transformer of transformers)
                tokenNode = ((_a3 = transformer == null ? void 0 : transformer.span) == null ? void 0 : _a3.call(context, tokenNode, idx + 1, col, lineNode, token)) || tokenNode;
            if (structure === "inline")
                root2.children.push(tokenNode);
            else if (structure === "classic")
                lineNode.children.push(tokenNode);
            col += token.content.length;
        }
        if (structure === "classic") {
            for (const transformer of transformers)
                lineNode = ((_b3 = transformer == null ? void 0 : transformer.line) == null ? void 0 : _b3.call(context, lineNode, idx + 1)) || lineNode;
            lineNodes.push(lineNode);
            lines.push(lineNode);
        }
    });
    if (structure === "classic") {
        for (const transformer of transformers)
            codeNode = ((_a2 = transformer == null ? void 0 : transformer.code) == null ? void 0 : _a2.call(context, codeNode)) || codeNode;
        preNode.children.push(codeNode);
        for (const transformer of transformers)
            preNode = ((_b2 = transformer == null ? void 0 : transformer.pre) == null ? void 0 : _b2.call(context, preNode)) || preNode;
        root2.children.push(preNode);
    }
    let result = root2;
    for (const transformer of transformers)
        result = ((_c = transformer == null ? void 0 : transformer.root) == null ? void 0 : _c.call(context, result)) || result;
    if (grammarState)
        setLastGrammarStateToMap(result, grammarState);
    return result;
}

function mergeWhitespaceTokens(tokens) {
    return tokens.map((line) => {
        const newLine = [];
        let carryOnContent = "";
        let firstOffset = 0;
        line.forEach((token, idx) => {
            const isUnderline = token.fontStyle && token.fontStyle & FontStyle.Underline;
            const couldMerge = !isUnderline;
            if (couldMerge && token.content.match(/^\s+$/) && line[idx + 1]) {
                if (!firstOffset)
                    firstOffset = token.offset;
                carryOnContent += token.content;
            } else {
                if (carryOnContent) {
                    if (couldMerge) {
                        newLine.push({
                            ...token,
                            offset: firstOffset,
                            content: carryOnContent + token.content
                        });
                    } else {
                        newLine.push(
                            {
                                content: carryOnContent,
                                offset: firstOffset
                            },
                            token
                        );
                    }
                    firstOffset = 0;
                    carryOnContent = "";
                } else {
                    newLine.push(token);
                }
            }
        });
        return newLine;
    });
}

function splitWhitespaceTokens(tokens) {
    return tokens.map((line) => {
        return line.flatMap((token) => {
            if (token.content.match(/^\s+$/))
                return token;
            const match = token.content.match(/^(\s*)(.*?)(\s*)$/);
            if (!match)
                return token;
            const [, leading, content, trailing] = match;
            if (!leading && !trailing)
                return token;
            const expanded = [{
                ...token,
                offset: token.offset + leading.length,
                content
            }];
            if (leading) {
                expanded.unshift({
                    content: leading,
                    offset: token.offset
                });
            }
            if (trailing) {
                expanded.push({
                    content: trailing,
                    offset: token.offset + leading.length + content.length
                });
            }
            return expanded;
        });
    });
}

function codeToHtml(internal, code, options) {
    var _a2;
    const context = {
        meta: {},
        options,
        codeToHast: (_code, _options) => codeToHast(internal, _code, _options),
        codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)
    };
    let result = toHtml(codeToHast(internal, code, options, context));
    for (const transformer of getTransformers(options))
        result = ((_a2 = transformer.postprocess) == null ? void 0 : _a2.call(context, result, options)) || result;
    return result;
}

const VSCODE_FALLBACK_EDITOR_FG = {light: "#333333", dark: "#bbbbbb"};
const VSCODE_FALLBACK_EDITOR_BG = {light: "#fffffe", dark: "#1e1e1e"};
const RESOLVED_KEY = "__shiki_resolved";

function normalizeTheme(rawTheme) {
    var _a2, _b2, _c, _d, _e;
    if (rawTheme == null ? void 0 : rawTheme[RESOLVED_KEY])
        return rawTheme;
    const theme = {
        ...rawTheme
    };
    if (theme.tokenColors && !theme.settings) {
        theme.settings = theme.tokenColors;
        delete theme.tokenColors;
    }
    theme.type || (theme.type = "dark");
    theme.colorReplacements = {...theme.colorReplacements};
    theme.settings || (theme.settings = []);
    let {bg, fg} = theme;
    if (!bg || !fg) {
        const globalSetting = theme.settings ? theme.settings.find((s) => !s.name && !s.scope) : void 0;
        if ((_a2 = globalSetting == null ? void 0 : globalSetting.settings) == null ? void 0 : _a2.foreground)
            fg = globalSetting.settings.foreground;
        if ((_b2 = globalSetting == null ? void 0 : globalSetting.settings) == null ? void 0 : _b2.background)
            bg = globalSetting.settings.background;
        if (!fg && ((_c = theme == null ? void 0 : theme.colors) == null ? void 0 : _c["editor.foreground"]))
            fg = theme.colors["editor.foreground"];
        if (!bg && ((_d = theme == null ? void 0 : theme.colors) == null ? void 0 : _d["editor.background"]))
            bg = theme.colors["editor.background"];
        if (!fg)
            fg = theme.type === "light" ? VSCODE_FALLBACK_EDITOR_FG.light : VSCODE_FALLBACK_EDITOR_FG.dark;
        if (!bg)
            bg = theme.type === "light" ? VSCODE_FALLBACK_EDITOR_BG.light : VSCODE_FALLBACK_EDITOR_BG.dark;
        theme.fg = fg;
        theme.bg = bg;
    }
    if (!(theme.settings[0] && theme.settings[0].settings && !theme.settings[0].scope)) {
        theme.settings.unshift({
            settings: {
                foreground: theme.fg,
                background: theme.bg
            }
        });
    }
    let replacementCount = 0;
    const replacementMap = /* @__PURE__ */ new Map();

    function getReplacementColor(value) {
        var _a3;
        if (replacementMap.has(value))
            return replacementMap.get(value);
        replacementCount += 1;
        const hex = "#".concat(replacementCount.toString(16).padStart(8, "0").toLowerCase());
        if ((_a3 = theme.colorReplacements) == null ? void 0 : _a3["#".concat(hex)])
            return getReplacementColor(value);
        replacementMap.set(value, hex);
        return hex;
    }

    theme.settings = theme.settings.map((setting) => {
        var _a3, _b3;
        const replaceFg = ((_a3 = setting.settings) == null ? void 0 : _a3.foreground) && !setting.settings.foreground.startsWith("#");
        const replaceBg = ((_b3 = setting.settings) == null ? void 0 : _b3.background) && !setting.settings.background.startsWith("#");
        if (!replaceFg && !replaceBg)
            return setting;
        const clone2 = {
            ...setting,
            settings: {
                ...setting.settings
            }
        };
        if (replaceFg) {
            const replacement = getReplacementColor(setting.settings.foreground);
            theme.colorReplacements[replacement] = setting.settings.foreground;
            clone2.settings.foreground = replacement;
        }
        if (replaceBg) {
            const replacement = getReplacementColor(setting.settings.background);
            theme.colorReplacements[replacement] = setting.settings.background;
            clone2.settings.background = replacement;
        }
        return clone2;
    });
    for (const key2 of Object.keys(theme.colors || {})) {
        if (key2 === "editor.foreground" || key2 === "editor.background" || key2.startsWith("terminal.ansi")) {
            if (!((_e = theme.colors[key2]) == null ? void 0 : _e.startsWith("#"))) {
                const replacement = getReplacementColor(theme.colors[key2]);
                theme.colorReplacements[replacement] = theme.colors[key2];
                theme.colors[key2] = replacement;
            }
        }
    }
    Object.defineProperty(theme, RESOLVED_KEY, {
        enumerable: false,
        writable: false,
        value: true
    });
    return theme;
}

async function resolveLangs(langs) {
    return Array.from(new Set((await Promise.all(
        langs.filter((l) => !isSpecialLang(l)).map(async (lang) => await normalizeGetter(lang).then((r) => Array.isArray(r) ? r : [r]))
    )).flat()));
}

async function resolveThemes(themes) {
    const resolved = await Promise.all(
        themes.map(
            async (theme) => isSpecialTheme(theme) ? null : normalizeTheme(await normalizeGetter(theme))
        )
    );
    return resolved.filter((i) => !!i);
}

class Registry2 extends Registry$1 {
    constructor(_resolver, _themes, _langs, _alias = {}) {
        super(_resolver);
        __publicField(this, "_resolvedThemes", /* @__PURE__ */ new Map());
        __publicField(this, "_resolvedGrammars", /* @__PURE__ */ new Map());
        __publicField(this, "_langMap", /* @__PURE__ */ new Map());
        __publicField(this, "_langGraph", /* @__PURE__ */ new Map());
        __publicField(this, "_textmateThemeCache", /* @__PURE__ */ new WeakMap());
        __publicField(this, "_loadedThemesCache", null);
        __publicField(this, "_loadedLanguagesCache", null);
        this._resolver = _resolver;
        this._themes = _themes;
        this._langs = _langs;
        this._alias = _alias;
        this._themes.map((t) => this.loadTheme(t));
        this.loadLanguages(this._langs);
    }

    getTheme(theme) {
        if (typeof theme === "string")
            return this._resolvedThemes.get(theme);
        else
            return this.loadTheme(theme);
    }

    loadTheme(theme) {
        const _theme = normalizeTheme(theme);
        if (_theme.name) {
            this._resolvedThemes.set(_theme.name, _theme);
            this._loadedThemesCache = null;
        }
        return _theme;
    }

    getLoadedThemes() {
        if (!this._loadedThemesCache)
            this._loadedThemesCache = [...this._resolvedThemes.keys()];
        return this._loadedThemesCache;
    }

    // Override and re-implement this method to cache the textmate themes as `TextMateTheme.createFromRawTheme`
    // is expensive. Themes can switch often especially for dual-theme support.
    //
    // The parent class also accepts `colorMap` as the second parameter, but since we don't use that,
    // we omit here so it's easier to cache the themes.
    setTheme(theme) {
        let textmateTheme = this._textmateThemeCache.get(theme);
        if (!textmateTheme) {
            textmateTheme = Theme.createFromRawTheme(theme);
            this._textmateThemeCache.set(theme, textmateTheme);
        }
        this._syncRegistry.setTheme(textmateTheme);
    }

    getGrammar(name) {
        if (this._alias[name]) {
            const resolved = /* @__PURE__ */ new Set([name]);
            while (this._alias[name]) {
                name = this._alias[name];
                if (resolved.has(name))
                    throw new ShikiError3("Circular alias `".concat(Array.from(resolved).join(" -> "), " -> ").concat(name, "`"));
                resolved.add(name);
            }
        }
        return this._resolvedGrammars.get(name);
    }

    loadLanguage(lang) {
        var _a2, _b2, _c, _d;
        if (this.getGrammar(lang.name))
            return;
        const embeddedLazilyBy = new Set(
            [...this._langMap.values()].filter((i) => {
                var _a3;
                return (_a3 = i.embeddedLangsLazy) == null ? void 0 : _a3.includes(lang.name);
            })
        );
        this._resolver.addLanguage(lang);
        const grammarConfig = {
            balancedBracketSelectors: lang.balancedBracketSelectors || ["*"],
            unbalancedBracketSelectors: lang.unbalancedBracketSelectors || []
        };
        this._syncRegistry._rawGrammars.set(lang.scopeName, lang);
        const g = this.loadGrammarWithConfiguration(lang.scopeName, 1, grammarConfig);
        g.name = lang.name;
        this._resolvedGrammars.set(lang.name, g);
        if (lang.aliases) {
            lang.aliases.forEach((alias) => {
                this._alias[alias] = lang.name;
            });
        }
        this._loadedLanguagesCache = null;
        if (embeddedLazilyBy.size) {
            for (const e of embeddedLazilyBy) {
                this._resolvedGrammars.delete(e.name);
                this._loadedLanguagesCache = null;
                (_b2 = (_a2 = this._syncRegistry) == null ? void 0 : _a2._injectionGrammars) == null ? void 0 : _b2.delete(e.scopeName);
                (_d = (_c = this._syncRegistry) == null ? void 0 : _c._grammars) == null ? void 0 : _d.delete(e.scopeName);
                this.loadLanguage(this._langMap.get(e.name));
            }
        }
    }

    dispose() {
        super.dispose();
        this._resolvedThemes.clear();
        this._resolvedGrammars.clear();
        this._langMap.clear();
        this._langGraph.clear();
        this._loadedThemesCache = null;
    }

    loadLanguages(langs) {
        for (const lang of langs)
            this.resolveEmbeddedLanguages(lang);
        const langsGraphArray = Array.from(this._langGraph.entries());
        const missingLangs = langsGraphArray.filter(([_, lang]) => !lang);
        if (missingLangs.length) {
            const dependents = langsGraphArray.filter(([_, lang]) => {
                var _a2;
                return lang && ((_a2 = lang.embeddedLangs) == null ? void 0 : _a2.some((l) => missingLangs.map(([name]) => name).includes(l)));
            }).filter((lang) => !missingLangs.includes(lang));
            throw new ShikiError3("Missing languages ".concat(missingLangs.map(([name]) => "`".concat(name, "`")).join(", "), ", required by ").concat(dependents.map(([name]) => "`".concat(name, "`")).join(", ")));
        }
        for (const [_, lang] of langsGraphArray)
            this._resolver.addLanguage(lang);
        for (const [_, lang] of langsGraphArray)
            this.loadLanguage(lang);
    }

    getLoadedLanguages() {
        if (!this._loadedLanguagesCache) {
            this._loadedLanguagesCache = [
                .../* @__PURE__ */ new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])
            ];
        }
        return this._loadedLanguagesCache;
    }

    resolveEmbeddedLanguages(lang) {
        this._langMap.set(lang.name, lang);
        this._langGraph.set(lang.name, lang);
        if (lang.embeddedLangs) {
            for (const embeddedLang of lang.embeddedLangs)
                this._langGraph.set(embeddedLang, this._langMap.get(embeddedLang));
        }
    }
}

class Resolver {
    constructor(engine, langs) {
        __publicField(this, "_langs", /* @__PURE__ */ new Map());
        __publicField(this, "_scopeToLang", /* @__PURE__ */ new Map());
        __publicField(this, "_injections", /* @__PURE__ */ new Map());
        __publicField(this, "_onigLib");
        this._onigLib = {
            createOnigScanner: (patterns) => engine.createScanner(patterns),
            createOnigString: (s) => engine.createString(s)
        };
        langs.forEach((i) => this.addLanguage(i));
    }

    get onigLib() {
        return this._onigLib;
    }

    getLangRegistration(langIdOrAlias) {
        return this._langs.get(langIdOrAlias);
    }

    loadGrammar(scopeName) {
        return this._scopeToLang.get(scopeName);
    }

    addLanguage(l) {
        this._langs.set(l.name, l);
        if (l.aliases) {
            l.aliases.forEach((a) => {
                this._langs.set(a, l);
            });
        }
        this._scopeToLang.set(l.scopeName, l);
        if (l.injectTo) {
            l.injectTo.forEach((i) => {
                if (!this._injections.get(i))
                    this._injections.set(i, []);
                this._injections.get(i).push(l.scopeName);
            });
        }
    }

    getInjections(scopeName) {
        const scopeParts = scopeName.split(".");
        let injections = [];
        for (let i = 1; i <= scopeParts.length; i++) {
            const subScopeName = scopeParts.slice(0, i).join(".");
            injections = [...injections, ...this._injections.get(subScopeName) || []];
        }
        return injections;
    }
}

let instancesCount = 0;

function createShikiInternalSync(options) {
    instancesCount += 1;
    if (options.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0)
        console.warn("[Shiki] ".concat(instancesCount, " instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call `highlighter.dispose()` to release unused instances."));
    let isDisposed = false;
    if (!options.engine)
        throw new ShikiError3("`engine` option is required for synchronous mode");
    const langs = (options.langs || []).flat(1);
    const themes = (options.themes || []).flat(1).map(normalizeTheme);
    const resolver = new Resolver(options.engine, langs);
    const _registry = new Registry2(resolver, themes, langs, options.langAlias);
    let _lastTheme;

    function getLanguage(name) {
        ensureNotDisposed();
        const _lang = _registry.getGrammar(typeof name === "string" ? name : name.name);
        if (!_lang)
            throw new ShikiError3("Language `".concat(name, "` not found, you may need to load it first"));
        return _lang;
    }

    function getTheme(name) {
        if (name === "none")
            return {bg: "", fg: "", name: "none", settings: [], type: "dark"};
        ensureNotDisposed();
        const _theme = _registry.getTheme(name);
        if (!_theme)
            throw new ShikiError3("Theme `".concat(name, "` not found, you may need to load it first"));
        return _theme;
    }

    function setTheme(name) {
        ensureNotDisposed();
        const theme = getTheme(name);
        if (_lastTheme !== name) {
            _registry.setTheme(theme);
            _lastTheme = name;
        }
        const colorMap = _registry.getColorMap();
        return {
            theme,
            colorMap
        };
    }

    function getLoadedThemes() {
        ensureNotDisposed();
        return _registry.getLoadedThemes();
    }

    function getLoadedLanguages() {
        ensureNotDisposed();
        return _registry.getLoadedLanguages();
    }

    function loadLanguageSync(...langs2) {
        ensureNotDisposed();
        _registry.loadLanguages(langs2.flat(1));
    }

    async function loadLanguage(...langs2) {
        return loadLanguageSync(await resolveLangs(langs2));
    }

    function loadThemeSync(...themes2) {
        ensureNotDisposed();
        for (const theme of themes2.flat(1)) {
            _registry.loadTheme(theme);
        }
    }

    async function loadTheme(...themes2) {
        ensureNotDisposed();
        return loadThemeSync(await resolveThemes(themes2));
    }

    function ensureNotDisposed() {
        if (isDisposed)
            throw new ShikiError3("Shiki instance has been disposed");
    }

    function dispose() {
        if (isDisposed)
            return;
        isDisposed = true;
        _registry.dispose();
        instancesCount -= 1;
    }

    return {
        setTheme,
        getTheme,
        getLanguage,
        getLoadedThemes,
        getLoadedLanguages,
        loadLanguage,
        loadLanguageSync,
        loadTheme,
        loadThemeSync,
        dispose,
        [Symbol.dispose]: dispose
    };
}

async function createShikiInternal(options) {
    if (options.loadWasm) {
        warnDeprecated("`loadWasm` option is deprecated. Use `engine: createOnigurumaEngine(loadWasm)` instead.");
    }
    if (!options.engine) {
        warnDeprecated("`engine` option is required. Use `createOnigurumaEngine` or `createJavaScriptRegexEngine` to create an engine.");
    }
    const [
        themes,
        langs,
        engine
    ] = await Promise.all([
        resolveThemes(options.themes || []),
        resolveLangs(options.langs || []),
        options.engine || createOnigurumaEngine(options.loadWasm || getDefaultWasmLoader())
    ]);
    return createShikiInternalSync({
        ...options,
        themes,
        langs,
        engine
    });
}

async function createHighlighterCore(options) {
    const internal = await createShikiInternal(options);
    return {
        getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),
        codeToTokensBase: (code, options2) => codeToTokensBase(internal, code, options2),
        codeToTokensWithThemes: (code, options2) => codeToTokensWithThemes(internal, code, options2),
        codeToTokens: (code, options2) => codeToTokens(internal, code, options2),
        codeToHast: (code, options2) => codeToHast(internal, code, options2),
        codeToHtml: (code, options2) => codeToHtml(internal, code, options2),
        ...internal,
        getInternalContext: () => internal
    };
}

const shiki = shallowRef();
const isShikiLoading = ref(true);
const shikiLoadError = ref(null);
const SUPPORTED_LANGUAGES = {
    sql: () => __vitePreload(() => import("./sql-DPX3FHqF.js"), true ? [] : void 0),
    json: () => __vitePreload(() => import("./json-DahFuqmc.js"), true ? [] : void 0),
    python: () => __vitePreload(() => import("./python-V6flNjh3.js"), true ? [] : void 0),
    javascript: () => __vitePreload(() => import("./javascript-D3BEr4GS.js"), true ? [] : void 0),
    bash: () => __vitePreload(() => import("./bash--KGRf1q4.js"), true ? [] : void 0),
    java: () => __vitePreload(() => import("./java-DWlk4OCa.js"), true ? [] : void 0)
};

async function initializeShiki() {
    try {
        isShikiLoading.value = true;
        const highlighter = await createHighlighterCore({
            engine: createOnigurumaEngine(() => __vitePreload(() => import("./wasm-DDgzZJey.js"), true ? [] : void 0)),
            themes: [
                __vitePreload(() => import("./github-light-BTbR9xVK.js"), true ? [] : void 0)
            ],
            langs: Object.values(SUPPORTED_LANGUAGES).map((lang) => lang())
        });
        shiki.value = highlighter;
    } catch (error) {
        shikiLoadError.value = error;
        console.error("Failed to initialize Shiki:", error);
    } finally {
        isShikiLoading.value = false;
    }
}

initializeShiki();
const _hoisted_1 = ["innerHTML"];
const _sfc_main = /* @__PURE__ */ defineComponent({
    __name: "ShikiCode",
    props: {
        code: {},
        lang: {},
        theme: {default: "github-light"}
    },
    setup(__props) {
        const props = __props;
        const highlighted = shallowRef("");
        watchEffect(() => {
            try {
                if (!shiki.value) {
                    highlighted.value = escapeHtml(props.code);
                    return;
                }
                highlighted.value = shiki.value.codeToHtml(props.code, {
                    lang: props.lang,
                    theme: props.theme,
                    transformers: [
                        {
                            pre(node) {
                                node.properties.style = "white-space: break-spaces;overflow-wrap: break-word;";
                            }
                        }
                    ]
                });
            } catch (error) {
                console.error("Failed to highlight code:", error);
                highlighted.value = escapeHtml(props.code);
            }
        });
        return (_ctx, _cache) => {
            return openBlock(), createElementBlock("div", {
                class: "p-4",
                innerHTML: unref(highlighted)
            }, null, 8, _hoisted_1);
        };
    }
});

function useCopy() {
    const copied = ref(false);
    const timeout = useTimeoutFn(() => copied.value = false, 1500);

    async function copy(textToCopy) {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(textToCopy);
            copied.value = true;
            timeout.start();
        } else {
            const textArea = document.createElement("textarea");
            textArea.value = textToCopy;
            textArea.style.position = "absolute";
            textArea.style.opacity = "0";
            textArea.style.left = "-999999px";
            textArea.style.top = "-999999px";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            document.execCommand("copy");
            textArea.remove();
            copied.value = true;
            timeout.start();
        }
    }

    return {
        copied,
        copy
    };
}

export {
    _sfc_main as _,
    useCopy as u
};
